日期差异包括时区偏移,有什么问题吗?
我有这样的代码:
Date now = new Date();
// the string is in UTC format, so a UTC date must be constructed, I don't know if that happens in this format
Date measure = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(utcDateTime);
long diff = now.getTime() - measure.getTime();
if (diff < 1000* 60 * 15) {
// measure is less then 15 minutes recent
do some work
}
当我得到差异时,它包括时区。我知道 Date 对象内部是 UTC。
那么这里出了什么问题呢?
I have this code:
Date now = new Date();
// the string is in UTC format, so a UTC date must be constructed, I don't know if that happens in this format
Date measure = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(utcDateTime);
long diff = now.getTime() - measure.getTime();
if (diff < 1000* 60 * 15) {
// measure is less then 15 minutes recent
do some work
}
When I get the diff, it includes the timezone. I know the Date object internally is UTC.
So what's wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然
Date
对象确实采用 UTC,但您的SimpleDateFormat
可能不是。我怀疑它默认是系统时区 - 这肯定是实验所建议的。您可以使用DateFormat.setTimeZone
更改此设置。因此,如果您的文本表示 UTC 日期/时间,您也应该将格式化程序的时区设置为 UTC。或者您可以使用 Joda Time,这是一个通常更好的日期和时间 API :)
While a
Date
object is indeed in UTC, yourSimpleDateFormat
may not be. I suspect it default's to the system time zone - that's certainly what experimentation would suggest. You can change this usingDateFormat.setTimeZone
. So if your text represents a UTC date/time, you should set the time zone of the formatter to UTC as well.Or you could use Joda Time, which is a generally better date and time API :)