java - 为 Epoch 使用不同的初始日期

标签 java date timestamp epoch

全部,

我正在使用一个二进制规范,其时间戳字段定义为“自 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/

相关文章:

java - 计算两个 Java 日期实例之间的差异

PHP 相当于 javascript 中的 Date.UTC 函数?

mysql - 在 SQL 语句中进行数学运算?

java - 结果超过 24 小时的时间总和

javascript - 如何将日期转换为时间戳字符串 Angular 2

java - redis.clients.jedis.exceptions.JedisConnectionException : Could not get a resource from the pool

java - .jar 文件无法运行? (我觉得我错过了一些明显的东西,在来这里之前自己寻找解决方案。)

java - 如何从不同的类将 JPanel 添加到 JFrame

java - 使用 REST Api 删除 OTDS 用户 - 无法删除同步对象

java - 返回另一个类的时间