我有一個 LocalDateTime 物件,我想獲取該月的最后一天。所以如果 localDateTime 指向今天的 10 月 29 日。我想將其轉換為 10 月 31 日
是否有一種干凈且簡單的方法?
我的想法:
一種方法是獲取月份,然后進行 switch 陳述句。但這將是漫長而乏味的方法。不確定是否有內置的方法
來做同樣的事情
uj5u.com熱心網友回復:
使用YearMonth.atEndOfMonth
LocalDate date = LocalDate.now();
YearMonth month = YearMonth.from(date);
LocalDate end = month.atEndOfMonth();
uj5u.com熱心網友回復:
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String args[]) {
LocalDateTime a = LocalDateTime.of(2021, 10, 29, 0, 0);
LocalDateTime b = a.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(a);
System.out.println(b);
}
}
uj5u.com熱心網友回復:
你問:
如何將一天的結束時間添加到 localDateTime。我看到一個名為 LocalTime.MAX 的選項,但它添加了尾隨 .99999
LocalDateTime如果您要跟蹤時刻、時間線上的特定點,請不要使用。該類缺少時區或UTC偏移量的背景關系。對于時刻,使用Instant,OffsetDateTime或ZonedDateTime。
用 表示整個月YearMonth。
你不應該試圖確定這個月的最后時刻。最后一刻是無限可分割的。通常,定義時間跨度的最佳方法是半開放方法而不是完全封閉方法。在半開中,開頭是包容的,而結尾是獨占的。
因此,一天從一天的第一時刻開始,一直到(但不包括)第二天的第一時刻。一個月與當月的第一天的第一刻開始,運行到,但不包括,第一個的第一時刻接下來一個月。
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
YearMonth currentMonth = YearMonth.now( z ) ;
YearMonth followingMonth = currentMonth.plusMonths( 1 ) ;
ZonedDateTime start = currentMonth.atDay( 1 ).atStartOfDay( z ) ;
ZonedDateTime end = followingMonth.atDay( 1 ).atStartOfDay( z ) ;
要表示該時間跨度,請將ThreeTen-Extra庫添加到您的專案中。使用Interval其方便的比較方法,如類abuts,overlaps和contains。
org.threeten.extra.Interval interval = Interval.of( start.toInstant() , end.toInstant() ) ;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341712.html
下一篇:掃雷程式超過時限
