首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何基于YearMonth和给定的年份和月份启动ZoneId?

如何基于YearMonth和给定的年份和月份启动ZoneId?
EN

Stack Overflow用户
提问于 2021-11-01 13:32:14
回答 1查看 90关注 0票数 1

我有以下方法来计算给定月份的长度(以秒为单位)。

代码语言:javascript
复制
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包括在下面的行中呢?

代码语言:javascript
复制
YearMonth.of(year, month).lengthOfMonth();

要点:我知道,我可以初始化YearMonth.now(ZoneId),但是它看起来工作量太大,无法得到最终的答案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-01 13:44:12

tl;dr

代码语言:javascript
复制
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()

详细信息

你必须决定这个月的第一分钟。

代码语言:javascript
复制
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;

YearMonth ym = YearMonth.of( year , month ) ;
LocalDate firstOfMonth = ym.atDay( 1 ) ;
ZonedDateTime start = firstOfMonth.atStartOfDay( z ) ;

然后决定下个月的第一分钟。

代码语言:javascript
复制
YearMonth followingMonth = ym.plusMonths( 1 ) ;
LocalDate firstOfFollowingMonth = followingMonth.atDay( 1 ) ;
ZonedDateTime end = firstOfFollowingMonth.atStartOfDay( z ) ;

计算经过的时间。

代码语言:javascript
复制
Duration d = Duration.between( start , end ) ;
long seconds = d.toSeconds() ;

你说过:

本代码不考虑冬季时间和春季时间的ZoneId。

夏令时(DST)并不是时钟异常的唯一原因。政治家改变在其管辖范围内用于各种外交、军事和政治目的的抵消。作为程序员,即使在不遵守DST的地方,我们也应该考虑对偏移量可能发生的更改。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69797666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档