How to obtain the end of the day when given a LocalDate?

故事扮演 提交于 2019-11-27 14:18:29

问题


How to obtain the end of the day when given a LocalDate?

I could get it by doing

LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));

But is there an equivalent 'atStartOfDay' method for the end of the day?

LocalDate.now().atStartOfDay();
LocalDate.now().atEndOfDay(); //doesn't work

回答1:


Here are a few alternatives, depending on what you need:

LocalDate.now().atTime(23, 59, 59);     //23:59:59
LocalDate.now().atTime(LocalTime.MAX);  //23:59:59.999999999

But there is no built-in method.

As commented by @JBNizet, if you want to create an interval, you can also use an interval up to midnight, exclusive.




回答2:


These are the variants available in LocalTime, notice MIDNIGHT and MIN are equal.

LocalDate.now().atTime(LocalTime.MIDNIGHT); //00:00:00.000000000
LocalDate.now().atTime(LocalTime.MIN);      //00:00:00.000000000
LocalDate.now().atTime(LocalTime.NOON);     //12:00:00.000000000
LocalDate.now().atTime(LocalTime.MAX);      //23:59:59.999999999

For reference, this is the implementation in java.time.LocalTime

/**
 * Constants for the local time of each hour.
 */
private static final LocalTime[] HOURS = new LocalTime[24];
static {
    for (int i = 0; i < HOURS.length; i++) {
        HOURS[i] = new LocalTime(i, 0, 0, 0);
    }
    MIDNIGHT = HOURS[0];
    NOON = HOURS[12];
    MIN = HOURS[0];
    MAX = new LocalTime(23, 59, 59, 999_999_999);
}



回答3:


Get start of next day and subtract 1 second from it. This should work for you. :

public static void main(String[] args) {

    LocalDate date = LocalDate.now();
    LocalDateTime dt = date.atStartOfDay().plusDays(1).minusSeconds(1);
    System.out.println(dt);
}

O/P :

2016-04-04T23:59:59


来源:https://stackoverflow.com/questions/36408548/how-to-obtain-the-end-of-the-day-when-given-a-localdate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!