【问题标题】:Converting timestamp to days and back results in a different date将时间戳转换为天数并返回会导致不同的日期
【发布时间】:2012-06-28 06:31:20
【问题描述】:

我需要存储不含时区信息的年月日信息。
这是一些代码:

private static void test() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("US/Pacific"));
    System.out.println("Before: " + cal.get(DAY_OF_MONTH));
    //
    long datestamp = toDatestamp(cal.getTimeInMillis());
    long timestamp = toTimestamp(datestamp);
    cal.setTimeInMillis(timestamp);
    System.out.println("After: " + cal.get(DAY_OF_MONTH));
}

private static long toTimestamp(long datestamp) {
    return TimeUnit.DAYS.toMillis(datestamp);
    // return datestamp * DS_MULT;
}

private static long toDatestamp(long timestamp) {
    return TimeUnit.MILLISECONDS.toDays(timestamp);
    // return timestamp / DS_MULT;
}

// hours * minutes * seconds * milliseconds
private static long DS_MULT = 24 * 60 * 60 * 1000;

有两种方法,其中一种被注释掉了。但结果是一样的:

Before: 26
After: 25

为什么转换后日期会改变?我错过了什么明显的东西吗?

【问题讨论】:

  • DAY_OF_MONTH 是什么?它在哪里定义?
  • 那是import static java.util.Calendar.DAY_OF_MONTH;
  • 您能否更清楚地描述您的问题是什么,以及您想用您的代码实现什么?

标签: java calendar timestamp


【解决方案1】:

通过转换为天数再转换回毫秒数,您实际上是在将日历重新设置为当天的午夜。但是,当您以毫秒为单位设置时间时,它会被解释为 UTC 时间(大致相当于 GMT),因此您将日历重置为午夜 UTC。因为“美国/太平洋”时区与 UTC 有负偏移,所以它显示为前一天。

您可以通过在测试末尾添加另一行来看到这一点:

cal.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC: " + cal.get(DAY_OF_MONTH));

你应该看到:

UTC: 26

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多