[英]Convert UTC time to local time while using the local year/month/day and specifying the hours/minutes JAVA
我正在嘗試將 09:00 UTC 轉換為本地等價物,如下所示:
ZoneId localZoneId = ZoneId.of(TimeZone.getDefault().getID());
DateTimeFormatter formatt = DateTimeFormatter.ofPattern("HH:mm").withZone(localZoneId);
ZonedDateTime test = ZonedDateTime.of( 2020 , 4 , 25 , 9 , 0 , 0 , 0 , ZoneId.of("UTC"));
String test2 = formatt.format(test);
System.out.println(test);
System.out.println(test2);
Output
2020-04-25T09:00Z[UTC]
02:00
但是,我不想手動輸入年、月和日,而是想從本地機器獲取當前的年、月、日,但仍將小時/分鍾保持在 09:00。這部分代碼需要像這樣工作
ZonedDateTime test = ZonedDateTime.of( currentYear, currentMonth , currentDay, 9 , 0 , 0 , 0 , ZoneId.of("UTC"));
正在考慮這樣做,但似乎有很多代碼:
ZonedDateTime dateparse= ZonedDateTime.now();
ZoneId localZoneId = ZoneId.of(TimeZone.getDefault().getID());
DateTimeFormatter formatFullLocal = DateTimeFormatter.ofPattern("HH:mm").withZone(localZoneId);
DateTimeFormatter year = DateTimeFormatter.ofPattern("yy");
String localMachineYearString= year.format(dateparse);
int localMachineYearInt = Integer.parseInt(localMachineYearString);
DateTimeFormatter month= DateTimeFormatter.ofPattern("M");
String localMachineMonthString= month.format(dateparse);
int localMachineMonthInt= Integer.parseInt(localMachineMonthString);
DateTimeFormatter day= DateTimeFormatter.ofPattern("dd");
String localMachineDayString= day.format(dateparse);
int localMachineDayInt= Integer.parseInt(localMachineDayString);
ZonedDateTime test =ZonedDateTime
.of(localMachineYearInt, localMachineMonthInt , localMachineDayInt , 9 , 0 , 0 , 0 , ZoneId.of("UTC"));
謝謝你!
ZonedDateTime.now().with( LocalTime.of( 9 , 0 ) )
LocalTime
object 傳遞給with
方法時,充當TemporalAdjuster
,以移動到不同的日期時間值。 該值是在一個全新的 object 中提供的,而不是更改原始的,作為不可變對象。
上面的代碼行隱含地依賴於 JVM 當前的默認時區。 最好明確指定。
順便說一句,不要將舊的日期時間類與java.time類混合。 完全避免遺留類。 所以這:
ZoneId localZoneId = ZoneId.of(TimeZone.getDefault().getID());
…應該:
ZoneId localZoneId = ZoneId.systemDefault() ;
此外, java.time中的“本地”表示“未分區”,或者區域/偏移量未知或未指定。 所以你的變量名localZoneId
令人困惑。 應該是這樣的:
ZoneId zoneId = ZoneId.systemDefault() ;
你說:
我想從本地機器上獲取當前的年月日
確定當前日期需要時區。 對於任何給定的時刻,日期在全球范圍內因時區而異。
ZoneId z = ZoneId.systemDefault() ;
LocalDate today = LocalDate.now( z ) ;
你說:
但仍將小時/分鍾保持在 09:00
ZonedDateTime
在時區的上下文中表示日期和時間。 您可以在工廠方法ZonedDateTime.of
中指定這三個部分中的每一個。
LocalTime lt = LocalTime.of( 9 , 0 ) ;
ZonedDateTime zdt = ZonedDateTime.of( today , lt , z ) ; // Pass date, time, zone.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.