sábado, 26 de septiembre de 2015

Java: Convert Dates between TimeZones before Java 8

Use case:

Your server is hosted in country with a different time zone than the country your consumers reside and, of course, they are expecting your date-based methods to be expressed in their time zone.

You cannot upgrade to Java 8 and some methods are already created, you just can send a date, which is time zone unaware.

Solution:

Deceive your classes into believing current time is different than the real time by offsetting time in milliseconds according to the difference in time zones:



public class DateUtil {
  
 protected static Date convertToTimeZone(String timezone, Date date) {
  Calendar timeZonedCal = GregorianCalendar.getInstance(TimeZone.getTimeZone(timezone));
  timeZonedCal.setTime(date);
  
  Calendar localCal = GregorianCalendar.getInstance();
  
  localCal.set(
    timeZonedCal.get(Calendar.YEAR)
    , timeZonedCal.get(Calendar.MONTH)
    , timeZonedCal.get(Calendar.DAY_OF_MONTH)
    , timeZonedCal.get(Calendar.HOUR_OF_DAY)
    , timeZonedCal.get(Calendar.MINUTE)
    , timeZonedCal.get(Calendar.SECOND));
  
  return localCal.getTime();
 }

 // TRY IT:
 public static void main(String[] args) {
  
  System.out.println(convertToTimeZone("Asia/Singapore", new Date()));
  System.out.println(convertToTimeZone("America/New_York", new Date()));
 }
}


 This was used to deceive log4j 1 to rotate the files in an appropriate date, by extending RollingPolicyBase and converting current date into time-zoned date. I can share the code in another entry if someones is interested.


* Source code was formatted with: http://hilite.me/

No hay comentarios:

Publicar un comentario