日期转换不正确

时间:2017-05-05 10:20:12

标签: android android-dateutils

今天是五月五日。以下代码应输出4月11日和4月10日。相反,我得到四月十一日和五月二十九日。这是代码:

    int daysBack = 24;
    long dayBeginningMilis = getTodaysBeginningMilis() - 86400000 * daysBack;
    Log.i(TAG, "Date: " + new Date(dayBeginningMilis));

    daysBack = 25;
    dayBeginningMilis = getTodaysBeginningMilis() - 86400000 * daysBack;
    Log.i(TAG, "Date: " + new Date(dayBeginningMilis));

private long getTodaysBeginningMilis() {

    // Get milis of todays beginning
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.setTimeZone(TimeZone.getTimeZone("Europe/Kiev"));

    return calendar.getTimeInMillis();

}

输出:

Date: Tue Apr 11 00:00:00 EEST 2017
Date: Mon May 29 17:02:47 EEST 2017

为什么会这样?

1 个答案:

答案 0 :(得分:1)

我找到了罪魁祸首。似乎乘法整数使它们超出范围并且它们不会自动转换为Long。这一变化解决了这个问题:

long daysBack = 24L;
long dayBeginningMilis = getTodaysBeginningMilis() - 86400000L * daysBack;
Log.i(TAG, "Date: " + new Date(dayBeginningMilis));

daysBack = 25L;
dayBeginningMilis = getTodaysBeginningMilis() - 86400000L * daysBack;
Log.i(TAG, "Date: " + new Date(dayBeginningMilis));