Home > database >  How can I initiate YearMonth based on ZoneId and a given year and month?
How can I initiate YearMonth based on ZoneId and a given year and month?

Time:11-02

I have the following method to calculate the length of a given month in seconds.

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

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

The problem is, this code does not consider the ZoneId for the Winter-Time and Spring-Time.

So, is there anyways that I can include the ZoneId into the below line ?

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

Point: I know, i can initialize the YearMonth.now(ZoneId), but then it looks too much work to get the final answer.

CodePudding user response:

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()

Details

You must determine the first moment of the month.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;

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

And determine the first moment of the following month.

YearMonth followingMonth = ym.plusMonths( 1 ) ;
LocalDate firstOfFollowingMonth = followingMonth.atDay( 1 ) ;
ZonedDateTime end = firstOfFollowingMonth.atStartOfDay( z ) ;

Calculate elapsed time.

Duration d = Duration.between( start , end ) ;
long seconds = d.toSeconds() ;

You said:

this code does not consider the ZoneId for the Winter-Time and Spring-Time.

Daylight Saving Time (DST) is not the only reason for clock anomalies. Politicians change the offset(s) used within their jurisdiction for various diplomatic, military, and political purposes. As programmers, we should always account for possible changes to the offset even in places not observing DST.

  • Related