java比较时间sql,如何比较日历的时间和java.sql.Time对象?

I want to know whether the Time values of a Calendar object equal the value of a java.sql.Time object.

E.g

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

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

I tried

t.equals(c.getTime())

But because the Calendar has Date information the expression is false.

What would be the best way the compare the two?

Edit:

The Time object is retrieve though Hibernate and come with no date information.

The Calendar object is create by

Calendar c= Calendar.getInstance();

c.set(Calendar.HOUR_OF_DAY, 9);

c.set(Calendar.MINUTE, 0);

c.set(Calendar.SECOND, 0);

解决方案

The way you use is perfectly fine. The goal is unclear, though. Why do you want c to be equal to d?

Additionally, there's no way to have d.toString() == "09:00:00" — Date always have, well, the date included.

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.

Update: now that you've mentioned it's actually java.sql.Time, I'm worried. The problem is,

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's default TZ

Calendar's TZ

All three must be the same so that any comparison would make any sense.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值