我有以下方法来计算给定月份的长度(以秒为单位)。
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),但是它看起来工作量太大,无法得到最终的答案。
发布于 2021-11-01 13:44:12
tl;dr
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://stackoverflow.com/questions/69797666
复制相似问题