Java 给定LocalDate时如何获得一天的结束时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36408548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:51:11  来源:igfitidea点击:

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

javajava-time

提问by cooxie

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

给定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?

但是一天结束时是否有等效的“atStartOfDay”方法?

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

采纳答案by assylias

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.

正如@JBNizet 所评论的,如果你想创建一个间隔,你也可以使用一个直到午夜的间隔,独占。

回答by TheLostMind

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

开始第二天并从中减去 1 秒。这应该对你有用。:

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

回答by Robert Hunt

These are the variants available in LocalTime, notice MIDNIGHTand MINare equal.

这些是 中可用的变体LocalTime,注意MIDNIGHT并且MIN是相同的。

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

作为参考,这是在 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);
}