我有以下方法來計算給定月份的長度(以秒為單位)。
public static long getNumberOfSecondsInMonth(int year, int month) {
int daysInMonth = YearMonth.of(year, month).lengthOfMonth();
return daysInMonth * HOURS_IN_DAY * SECONDS_IN_AN_HOUR;
}
問題是,這段代碼沒有考慮冬季和春季的 ZoneId。
那么,無論如何我可以將其ZoneId包含在下面的行中?
YearMonth.of(year, month).lengthOfMonth();
要點:我知道,我可以初始化YearMonth.now(ZoneId),但是要獲得最終答案看起來作業量太大了。
uj5u.com熱心網友回復:
tl;博士
Duration
.between(
YearMonth.of( year , month ).atDay( 1 ).atStartOfDay( ZoneId.of( "Asia/Tokyo" ) ) ,
YearMonth.of( year , month ).plusMonths( 1 ).atDay( 1 ).atStartOfDay( ZoneId.of( "Asia/Tokyo" ) )
)
.toSeconds()
細節
您必須確定該月的第一個時刻。
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
YearMonth ym = YearMonth.of( year , month ) ;
LocalDate firstOfMonth = ym.atDay( 1 ) ;
ZonedDateTime start = firstOfMonth.atStartOfDay( z ) ;
并確定下個月的第一時刻。
YearMonth followingMonth = ym.plusMonths( 1 ) ;
LocalDate firstOfFollowingMonth = followingMonth.atDay( 1 ) ;
ZonedDateTime end = firstOfFollowingMonth.atStartOfDay( z ) ;
計算經過的時間。
Duration d = Duration.between( start , end ) ;
long seconds = d.toSeconds() ;
你說:
此代碼不考慮冬季和春季的 ZoneId。
夏令時 (DST) 不是時鐘例外的唯一原因。政客出于各種外交、軍事和政治目的更改其管轄范圍內使用的抵消。作為程式員,即使在不遵守 DST 的地方,我們也應該始終考慮偏移量的可能變化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344868.html
上一篇:將日期時間四舍五入到最接近的秒,而不是回傳四舍五入到天的日期
下一篇:根據日期時間和其他列創建新功能
