22/08/2019

[Java] Date and Time utilities

Since java 8 introduced the java.time package, a lot of useful objects and methods are now available without the need to import external libraries.

Here are some operations that might come in handy when dealing with LocalDate and LocalDateTime objects:

  • Convert String timezone (in format {Region}/{City} eg: "Europe/Rome") to ZoneOffset:
 public static ZoneOffset stringToZoneOffset(final String timezone){  
   final ZoneId zone = ZoneId.of(timezone);  
   return zone.getRules().getOffset(Instant.now());  
 }  

  • Retrieve the hours offset between UTC and a given timezone:
 public static int hoursOffsetFromUTC(final String timezone){  
   return ZoneId.of(timezone)  
              .getRules()  
              .getOffset(Instant.ofEpochMilli(1_498_329_000_000L))  
              .getTotalSeconds()/3600;  
 }  

  • Convert given time (in format HH:mm:ss) with specific timezone to UTC time:
 public static OffsetTime timeAndTimezoneAtUTC(final String time, final String timezone){  
   return LocalTime.parse(time, DateTimeFormatter.ISO_LOCAL_TIME)  
                .atOffset(stringToZoneOffset(timezone))  
                .withOffsetSameInstant(ZoneOffset.UTC);  
 }  

  • Convert date to epoch seconds (if we had a LocalDateTime, we wouldn't need to use atStartOfDay):
 public static Long localDateToEpoch(final LocalDate localDate){  
   return localDate.atStartOfDay(ZoneOffset.UTC).toEpochSecond();  
 }  

No comments:

Post a Comment

With great power comes great responsibility