[英]ZonedDateTime how to set min or max time?
如何將無效的ZonedDateTime的時間更改為fe:“ java.time.LocalTime.MIN”或“ java.time.LocalTime.MAX”?
ZonedDateTime date = ZonedDateTime.now();
這是一個很好的開始: ZonedDateTime startDate = date.withHour(0).withMinute(0).withSecond(0).withNano(0);
但是最好有: ZonedDateTime startDate = date.withTime(LocalTime.Min);
正確的方法是:
System.out.println(date.toLocalDate().atStartOfDay(date.getZone()));
System.out.println(date.toLocalDate()
.plusDays(1)
.atStartOfDay(date.getZone())
.minusNanos(1));
一個人可能很容易期望date.with(LocalTime.MIN)
和date.with(LocalTime.MAX)
來完成這項工作,並且它可能會給您帶來期望的結果。 請注意,由於過渡到夏令時(DST)和其他異常,在少數情況下,當天的該區域中不存在時間00:00(這是LocalTime.MIN
的定義)。 以上清楚地考慮了這一點,也使您的讀者毫無疑問地會遇到這種情況。
但是,如果您只需要比較日期,就擺脫一天中的時間並比較日期:
ZonedDateTime otherDate = ZonedDateTime.of(2018, 2, 20, 13, 45, 0, 0,
ZoneId.of("America/Santa_Isabel"));
if (date.toLocalDate().isAfter(otherDate.toLocalDate())) {
// ...
}
您可以使用.with(TemporalAdjuster)。 您可以使用TemporalAdjust.adjustInto(Temporal)來調整TemporalAdjuster:
https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjuster.html https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime .html
對於ZonedDateTime中的Time的最小值,這是很短的:
ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS);
它將從ZonedDateTime中斷(設置為零):小時,分鍾,秒和納秒。
而這是ZonedDateTime中Time的最大值:
ZonedDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(LocalTime.MAX.getNano());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.