对纪元使用不同的初始日期
所有,
我正在使用一个二进制规范,其时间戳字段定义为“自 2000 年 1 月 1 日 UTC 时间以来的毫秒数”。我正在进行以下计算:
public static final TimeZone UTC = TimeZone.getTimeZone("UTC") ;
public static final Calendar Y2K_EPOCH = Calendar.getInstance(UTC);
static {
Y2K_EPOCH.clear();
// Month is 0 based; day is 1 based. Reset time to be first second of January 1, 2000
Y2K_EPOCH.set(2000, 0, 1, 0, 0, 0);
}
public static final long MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH = Y2K_EPOCH.getTimeInMillis();
public static long getMillisecondsSinceY2K(Date date) {
long time = date.getTime();
if (time < MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH) {
throw new IllegalArgumentException("Date must occur after January 1, 2000");
}
return time - MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH;
}
我的问题是,这是在标准 Java Date 对象和此数据类型之间进行转换的正确方法吗?有更好的方法吗?我知道乔达时间,但如果我能帮助的话,我宁愿不引入外部依赖。
All,
I am working with a binary specification whose TimeStamp fields are defined as "Milliseconds since January 1, 2000 UTC time". I am doing the following calculation:
public static final TimeZone UTC = TimeZone.getTimeZone("UTC") ;
public static final Calendar Y2K_EPOCH = Calendar.getInstance(UTC);
static {
Y2K_EPOCH.clear();
// Month is 0 based; day is 1 based. Reset time to be first second of January 1, 2000
Y2K_EPOCH.set(2000, 0, 1, 0, 0, 0);
}
public static final long MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH = Y2K_EPOCH.getTimeInMillis();
public static long getMillisecondsSinceY2K(Date date) {
long time = date.getTime();
if (time < MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH) {
throw new IllegalArgumentException("Date must occur after January 1, 2000");
}
return time - MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH;
}
My question is, is this the correct way to do the conversion between standard Java Date objects and this datatype? Is there a better way of doing this? I know about Joda time but I'd rather not bring that external dependency in if I can help it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我觉得不错。
请注意,您可以更改
为
关于您对闰秒的担忧,这里是文档的摘录:
Looks good to me.
Note that you could change
to
Regarding your worry about leap seconds, here is an excerpt from the docs:
时间是一个棘手的混乱,尤其是 UTC 时间。假设您想要基于任意纪元的相当好的时间,像您所做的那样的简单减法应该没问题。如果您担心闰秒精度,我强烈建议您使用 Joda 或一些可靠的外部库。
Time is a tricky mess, especially UTC time. Assuming you want a pretty good time based of an arbitrary epoch, a simple subtraction like what you do should be fine. If you are worried about leap-seconds precision I would highly suggest you use Joda or some reliable external library.