【问题标题】:How can I initiate YearMonth based on ZoneId and a given year and month?如何根据 ZoneId 和给定的年份和月份启动 YearMonth?
【发布时间】:2021-11-01 13:32:14
【问题描述】:

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

public static long getNumberOfSecondsInMonth(int year, int month) {

    int daysInMonth = YearMonth.of(year, month).lengthOfMonth();
    return daysInMonth * HOURS_IN_DAY * SECONDS_IN_AN_HOUR;
  }

问题是,这段代码没有考虑 Winter-Time 和 Spring-Time 的 ZoneId。

那么,无论如何我可以将ZoneId 包含在下面的行中吗?

YearMonth.of(year, month).lengthOfMonth();

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

【问题讨论】:

    标签: java datetime


    【解决方案1】:

    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 的地方也是如此。

    【讨论】:

    • 我是否认为这需要调用 d.getSeconds() 来返回 OP 正在寻找的结果?
    • @mohammedkhan 是的。
    • @mohammedkhan 或者直接使用ChronoUnit.SECONDS.between()
    • @mohammedkhan 自 Java 9 以来一直存在。请参阅 this
    • @mohammedkhan 两种方法的效果相同。最初的getSeconds 方法是一个糟糕的设计选择,因为它破坏了封装,因为我们真的不应该知道秒的内部成员字段。在 Java 9 中,添加了 toSeconds 以与其他 to… 方法保持一致。所以toSeconds 更可取,但getSeconds 必须在Java 8 上使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2016-11-23
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多