java比较时间sql_关于datetime:如何将Calendar的时间与java.sql.Time对象进行比较?

我想知道Calendar对象的Time值是否等于java.sql.Time对象的值。

例如

Calendar c; //c.getTime().toString() =="Sat Jan 07 09:00:00 GMT 2012"

Time t;     //d.toString() =="09:00:00";

我试过了

t.equals(c.getTime())

但是因为日历具有日期信息,所以表达式为false。

比较这两者的最佳方法是什么?

编辑:

Time对象通过Hibernate检索,并且没有日期信息。

Calendar对象的创建者

Calendar c= Calendar.getInstance();

c.set(Calendar.HOUR_OF_DAY, 9);

c.set(Calendar.MINUTE, 0);

c.set(Calendar.SECOND, 0);

如何比较date.getTime()与calendar.getTimeInMilliSeconds()

@DhanushGopinath不会帮助OP

日期默认实现,由Date组成,我怀疑您应用了某些DateFormatter,它省略了Date组件

在@Narayan,请参阅我的编辑。 该日期是通过休眠获取的。

您使用的方式非常好。不过,目标尚不清楚。为什么要c等于d?

此外,没有办法使d.toString() =="09:00:00" — Date总是包含日期。

不过,更重要的是,Date没有时区信息(以前曾经有,但是不鼓励您触摸Date的这一部分),因此您无法从10:00 BST告诉09:00 UTC也就是说,除非您指定时区。您可以从Calendar c获取时区,并且它说明了您需要执行的操作:

从您的日期创建一个Calendar

从您已经使用的日历中复制时区

比较您感兴趣的Calendar字段。我想那将是小时,分钟,秒,也许是毫秒。

更新:现在您已经提到它实际上是java.sql.Time,我很担心。问题是,

SQL Server通常将时间存储为包含小时,分钟,秒等的结构。也就是说,存在隐式时区(SQL Server时区)

java.sql.Time将时间存储为自1970年1月1日的"零纪元"值以来的毫秒数。日期部分通常被剥离为1970年1月1日-但是此类不包含时区信息。 (同样,它确实可以,但是已经过时了。)

Calendar具有明确设置的时区

实际上,这意味着使用系统默认时区将来自服务器的时间转换为毫秒,然后读取该值并将其与具有自己时区的Calendar进行比较。

如果听起来令人困惑和脆弱,那是因为。因此,基本上,您具有三个时区:

SQL Server TZ

JVM的默认TZ

日历的TZ

所有这三个必须相同,以便进行任何比较都有意义。

查看我的更新。该日期是通过Hibernate获取的,我没有更改对象中的任何内容,而那正是toString()产生的。

抱歉,出于某种原因,我以为Id读为Date,但实际上它是sql.Time对象。我将再次更新我的问题。

好吧,我去吧。谢谢。

@AshBurlaczenko很抱歉使您的生活更加艰难-请参阅更新。您将需要检查系统中的许多设置,否则日期和时间会给您带来麻烦。

据我所知,这3个时区都具有相同的时区,我已经同意您从日期创建另一个日历并只比较所需字段的想法。到目前为止一切正常。谢谢。

@AshBurlaczenko欢迎:)玩得开心!

您可以使用Date,Calendar,GregorianCalendar , SimpleDateFormat`等类在Java中处理日期时间。让我们看一些例子。

SimpleDateFormat dayFormat = new SimpleDateFormat("D");

int _currentDay = Integer.parseInt(dayFormat.format(new Date(System.currentTimeMillis())));

SimpleDateFormat monthFormat = new SimpleDateFormat("M");

int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));

SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));

System.out.println(_currentDay+"/"+_currentMonth+"/"+_currentYear);

将基于当前毫秒显示当前日期。

String toDate ="07/1/2012";

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);

Calendar currentDateCal = Calendar.getInstance();

// Zero out the hour, minute, second, and millisecond.

currentDateCal.set(Calendar.HOUR_OF_DAY, 0);

currentDateCal.set(Calendar.MINUTE, 0);

currentDateCal.set(Calendar.SECOND, 0);

currentDateCal.set(Calendar.MILLISECOND, 0);

Date currentDate = currentDateCal.getTime();

Date toDt;

try

{

toDt = df.parse(toDate);

}

catch (ParseException e)

{

toDt = null;

System.out.println(e.getMessage());

}

if (currentDate.equals(toDt))

{

System.out.println(currentDate);  // Displays the current date.

//Rest of the stuff.

}

String toDate ="07/12/2012";

try

{

if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24))

{

System.out.println("True");

}

else

{

System.out.println("Untrue");

}

}

catch(ParseException ex)

{

Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

}

String toDateAsString ="07/12/2012";

Date toDate=null;

try

{

toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);

}

catch (ParseException ex)

{

Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

}

long toDateAsTimestamp = toDate.getTime();

long currentTimestamp = System.currentTimeMillis();

long getRidOfTime = 1000 * 60 * 60 * 24;

long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;

long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;

if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime)

{

System.out.println("True");

}

else

{

System.out.println("False");

}

JodaTime的变体:

String toDateAsString ="07/01/2012";

DateTime toDate = DateTimeFormat.forPattern("MM/d/yyyy").parseDateTime(toDateAsString);

DateTime now = new DateTime();

if (!toDate.toLocalDate().isBefore(now.toLocalDate()))

{

System.out.println("True");

}

else

{

System.out.println("False");

}

Date已被弃用-不正确,抱歉。

@alf:不建议使用不推荐使用的类,但是大多数方法都是.. docs.oracle.com/javase/7/docs/api/java/util/Date.html是正确的链接。

@naresh谢谢,我不好。但是我不会在意这些方法:Date是一个不错的类,不建议弃用,并且对于正确使用而言非常合适。

@狮子仍在误导,对不起。除了访问日期部分的遗留方法之外,java.util.Date本身没有什么错,OP始终没有使用。那么,为什么要吓him他离开一个工作正常的班级呢?

@alf :)我不是Date类的对手。我只是指出了这样做的可能方法。

好吧,您的答案开始于"大多数Date方法已被弃用。使用Calendar作为您的工作……"-没有人可以读懂您的想法,但是您的文字说:" Date is baaaad!" :)

@alf :)谁说Date是不好的。我没有通过我的回答表明这一点。在示例中,我确实确实在某处使用了Date和Calendar。

这是一笔交易:删除"大多数Date方法已被弃用"。部分无济于事,然后我会投票给您,否则一切都会很好。只是这部分似乎误导了我:)

@alf :)我的笑容很高兴地批准了您的交易,这些短语已被删除。非常感谢你。

我今天必须这样做,这篇文章中的答案帮助我解决了问题。我知道我所有的时区都与OP相同。而且我没有在遗留代码中使用Joda time的自由,因此为了使其他拥有相同条件的人受益,这就是我使用香草Java的方式。

方法:

由于继承自java.sql.Time,因此getTime()具有getTime()

java.util.Date。使用这种方法,可以创建一个

java.util.Date对象,仅表示自

Java时代。

为了进行比较,必须转换所需的java.util.Calendar

对象以生成表示另一个对象的java.util.Date对象

自Java时代以来的时间。

由于日期部分现在是相等的,因此2之间的任何比较

对象只会比较产生期望结果的时间部分。

没有更多的理由,下面是代码:

import java.sql.Time;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class Test {

/**

* Method to convert a calendar object to java's epoch date

* keeping only the time information

*/

public static Date toEpochDate(Calendar calendar) {

return new Date(Time.valueOf(new SimpleDateFormat("HH:mm:ss").format(calendar.getTime())).getTime());

}

public static void main(String[] args) {

// create any calendar object

Calendar someTime = Calendar.getInstance();

someTime.set(Calendar.HOUR_OF_DAY, 17);

someTime.set(Calendar.MINUTE, 0);

someTime.set(Calendar.SECOND, 0);

// convert it to java epoch date

Date someDate = toEpochDate(someTime);

// create a date object from java.sql.Time

Date fromSqlTime = new Date(Time.valueOf("17:00:00").getTime());

// now do the comparison

System.out.println("Some Date:" + someDate.toString());

System.out.println("Sql Time:" + fromSqlTime.toString());

System.out.println("Are they equal?" + someDate.equals(fromSqlTime));

}

}

上面产生了以下输出:

Some Date: Thu Jan 01 17:00:00 EST 1970

Sql Time: Thu Jan 01 17:00:00 EST 1970

Are they equal? true

使用上述方法,并通过将.equals()更改为.before()或.after(),可以创建各种时间比较方便的方法。

由于您用DateTime标记了这个问题,我假设您已经使用Joda

...

//Initialize Calendar and Date Object

DateTime d1 = new DateTime(c.getTime());

DateTime d2 = new DateTime(d.getTime());

// Convert d1 and d2 to LocalDate say ld1 and ld2 since, Java Date defaults to GMT

ld1.compareTo(ld2);

您为什么不比较时间以毫秒为单位?

Date d;

Calendar c;

System.out.println(d.getTime() == c.getTimeInMillis());

好吧,因为OP想要忽略日期,就像他在第一行中提到的那样?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import time # 获取当前时间并格式化 current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 在终端输出当前时间 print("当前时间:", current_time) # 引入Tkinter库 import tkinter as tk # 创建一个窗口 window = tk.Tk() window.geometry('300x300') window.title('电子日历') # 在窗口中添加一个Label,显示当前日期和时间 current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) time_label = tk.Label(window, text=current_time) time_label.pack() # 添加一个按钮,点击后可以显示当天相隔的天数 def show_diff_days(): today = datetime.datetime.today() selected_day = calendar.selection_get() diff = (selected_day - today).days tk.messagebox.showinfo('相隔天数', f'距离今天相隔{diff}天') diff_btn = tk.Button(window, text='计算与今天相隔天数', command=show_diff_days) diff_btn.pack() # 在窗口中添加一个日历控件,让用户可以选择日期 import calendar import datetime from tkinter import messagebox as messagebox def show_selected_date(): selected_day = calendar.selection_get() messagebox.showinfo('选择日期', f'您选择了日期:{selected_day}') calendar = calendar.Calendar(window) calendar.pack() ok_btn = tk.Button(window, text='确认', command=show_selected_date) ok_btn.pack() # 运行窗口 window.mainloop() # 引入SQLite3库 import sqlite3 # 创建或连接到数据库 conn = sqlite3.connect('calendar.db') # 创建用户事件表格 conn.execute('''CREATE TABLE events (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE TEXT NOT NULL, EVENT TEXT NOT NULL, REMIND_TIME TEXT);''') # 在表格中插入用户事件数据 def add_event(date, event, remind_time): conn.execute(f"INSERT INTO events (DATE,EVENT,REMIND_TIME) \ VALUES ('{date}','{event}','{remind_time}')") conn.commit()
最新发布
06-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值