全部,
我正在使用一个二进制规范,其时间戳字段定义为“自 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 对象和该数据类型之间进行转换的正确方法吗?有更好的方法吗?我知道 Joda 时间,但如果可以的话,我宁愿不引入这种外部依赖。
最佳答案
我觉得不错。
请注意,您可以更改
long time = date.getTime();
if (time < MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH)
...
到
if (date.before(Y2K_EPOCH))
...
关于您对闰秒的担忧,以下是文档的摘录:
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
关于java - 为 Epoch 使用不同的初始日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5554257/