如何比较日历的时间和java.sql.Time对象? [英] How to compare Calendar's time to java.sql.Time object?
问题描述
我想知道Calendar对象的Time值是否等于java.sql.Time对象的值。
I want to know whether the Time values of a Calendar object equal the value of a java.sql.Time object.
Eg
Calendar c; //c.getTime().toString() == "Sat Jan 07 09:00:00 GMT 2012"
Time t; //d.toString() == "09:00:00";
我尝试了
t.equals(c.getTime())
但因为日历有日期
编辑:
时间对象通过Hibernate检索,没有日期信息。
The Time object is retrieve though Hibernate and come with no date information.
日历对象由
Calendar c= Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 9);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
推荐答案
但目标不清楚。为什么要 c
等于 d
?
The way you use is perfectly fine. The goal is unclear, though. Why do you want c
to be equal to d
?
此外,没有办法让 d.toString()==09:00:00
- 日期
Additionally, there's no way to have d.toString() == "09:00:00"
— Date
always have, well, the date included.
更重要的是, Date
没有时区信息(以前一直有,但你不鼓励触摸 Date
的这一部分),所以你不能告诉 09:00 UTC
从 10:00 BST
- 这是,除非您指定时区。您可以从日历c
获取时区,并解释您需要做什么:
What's more important, though, is that Date
has no timezone information (well, it used to have, but you're discouraged to touch this part of Date
), so you cannot tell 09:00 UTC
from 10:00 BST
—that is, unless you specify the timezone. You can get the timezone from Calendar c
, and it sort of explains what you need to do:
- 从您的日期创建
日历
- 从您已使用的日历复制时区
- 比较您感兴趣的
日历
字段。
- Create a
Calendar
from your date - Copy timezone from the calendar you already use
- Compare the
Calendar
fields which are of interest for you. I suppose that will be hour, minute, second, and, perhaps, millisecond.
更新时间:现在,您可以按时,分,你提到它实际上是 java.sql.Time
,我很担心。问题是,
Update: now that you've mentioned it's actually java.sql.Time
, I'm worried. The problem is,
- SQL服务器通常将时间存储为包含小时,分钟,秒等的结构。也就是说, >隐含的时区(SQL Server时区)
-
java.sql.Time
将时间以零 值,1970年1月1日。日期部分通常被剥离到1970年1月1日 - 但是这个类不包含时区信息。 -
日历
有一个明确设置的时区
- SQL servers usually store time as a structure containing hours, minutes, seconds, etc. That is, there's an implied timezone (the SQL Server timezone)
java.sql.Time
stores time as milliseconds since "zero epoch" value of January 1, 1970. The date part is usually stripped to January 1, 1970 — but this class does not contain timezone information. (Well, again, it sort of does, but it's deprecated.)Calendar
has an explicitly set timezone
在实践中,它意味着,从服务器的时间使用系统默认时区转换为毫秒,然后您读取此值并将其与日历
有自己的时区。
What it means in practice is, that the time from the server gets converted into milliseconds using system default timezone, then you read this value and compare it with a Calendar
with its own timezone.
如果它听起来很混乱和脆弱,那是因为它是。所以基本上你有三个时区:
If it sounds confusing and fragile, that's because it is. So basically you have three timezones:
- SQL Server TZ
- JVM的默认TZ
- 日历的TZ
所有三个必须相同,因此任何比较都会有意义。
All three must be the same so that any comparison would make any sense.
这篇关于如何比较日历的时间和java.sql.Time对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!