第 java.util.Date 轮到一天结束

Round java.util.Date to end of day

我想将 java.util.Date 对象四舍五入到一天结束,例如四舍五入 2016-04-21T10:28:18.109Z2016-04-22T00:00:00.000Z.

我看到了 Java Date rounding, but wasn't able to find something compareable for the end of the day. It also is not the same as how to create a Java Date object of midnight today and midnight tomorrow?,因为我不想创建新的 Date(今天或明天午夜),而是基于任何给定日期的下一个午夜。

鉴于 DateUtils 的文档,我不确定我是否会相信它。

假设您只对 UTC 日感兴趣,您可以利用 Unix 纪元处于日期边界这一事实:

public static Date roundUpUtcDate(Date date) {
    long millisPerDay = TimeUnit.DAYS.toMillis(1);
    long inputMillis = date.getTime();
    long daysRoundedUp = (inputMillis + (millisPerDay - 1)) / millisPerDay;
    return new Date(daysRoundedUp * millisPerDay);
}

如果可能可以,我会强烈敦促您搬到java.timeAPI。

DateUtils.ceiling 符合您的目的。为字段值传递 Calendar.DATE

传统方式

@Test
public void testDateRound() throws ParseException {
    Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2016-04-21T10:28:18.109Z");
    System.out.println(date);
    Calendar cl = Calendar.getInstance();
    cl.setTime(date);
    cl.set(Calendar.HOUR_OF_DAY, 23);
    cl.set(Calendar.MINUTE, 59);
    cl.set(Calendar.SECOND, 59);
    cl.set(Calendar.MILLISECOND, 999);
    System.out.println(cl.getTime());
    cl.add(Calendar.MILLISECOND, 1);
    System.out.println(cl.getTime());
}

输出

Thu Apr 21 10:28:18 GMT+03:00 2016
Thu Apr 21 23:59:59 GMT+03:00 2016
Fri Apr 22 00:00:00 GMT+03:00 2016