Say the server timestamp right now is 2022-01-26 16:02:00 PDT, I want to return list of timezones that have just passed the midnight (day start), in this case, 16:02 PDT is 2 minutes past 00:00 UTC, so return [UTC] in this case. How do I return a list of zoneIds (from this set: ZoneId.getAvailableZoneIds()) for a given timestamp T?
CodePudding user response:
“PDT” is not a real time zone. I assume you meant America/Los_Angeles.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
Define your desired moment as a ZonedDateTime.
LocalDate ld = LocalDate.parse( "2022-01-26" ) ;
LocalTime lt = LocalTime.parse( "16:02" ) ;
ZonedDateTime target = ZonedDateTime.of( ld , lt , z ) ;
Get your set of time zone names by calling ZoneId.getAvailableZoneIds.
Set< String > names = ZoneId.getAvailableZoneIds() ;
Loop those zone names. Obtain a ZoneId object for each. Use that zone object to adjust our target into that zone. Then determine the first moment of the day in that zone on that date.
Your Question makes the mistake of assuming the day starts at 00:00. Not true. Some dates in some zones start at another time such as 01:00. Let java.time determine the first moment of the day.
Duration limit = Duration.ofMinutes( 5 ) ;
List< ZoneId > hits = new ArrayList <>( names.size() ) ;
for( String name : names )
{
ZoneId zoneId = ZoneId.of( name ) ;
ZonedDateTime zdt = target.withZoneSameInstant( ZoneId ) ;
ZonedDateTime startOfDay = zdt.toLocalDate().atZone( zoneId );
Duration d = Duration.between ( startOfDay , zdt ) ;
if( d.compareTo( limit ) <= 0 ) { hits.add( zoneId ) ; }
}
return List.of( hits ) ;
