Friday, November 2, 2012

Convert String to Timezone with or without Day Light Savings using JODA DateTime

Handing date and time using java.utils.Date or java.utils.Calendar can be a bit problematical especially when you have to do date and time conversions according to time zones. JODA-Time api is an excellent alternative to do so and provides clear and concise methods to handel date and time in an efficient way.
In this post, I'll show how to convert a raw date time string first into a datetime object and then converting it into a specific time zone related date and time. You can download the api from here .

A word of caution: do not use JODA with SDK date methods as java.utils.Date uses index 0 (jan is indexed as 0 etc) and JODA uses index 1 for months and even for days.

  //the raw date-time value, before formatting  
       String rawValue = "201210310300" ;  
       //output format of date or time  
       String format = "yy/MM/dd";  
       // get the timeZoneID  
       String timeZoneId = "America/Denver";  
       // get the dst value (true/false)  
       //if dst = false , offset = standard or raw offset  
       boolean dst = true;  
       // create a date formatter object to specify raw date-time string is in which format  
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddHHmm");  
       // convert rawValue String into DateTime Object in UTC  
       DateTime oldDateTime = dtf.parseDateTime(rawValue).withZoneRetainFields(DateTimeZone.UTC);  
       //object to store converted date-time  
       DateTime newDateTime = new DateTime();  
       // create a TimeZone object wrt America/Denver  
       TimeZone tz = TimeZone.getTimeZone(timeZoneId);  
       // Use timezone to create a DateTimeZone object  
       DateTimeZone dtz = DateTimeZone.forTimeZone(tz);  
       // calculate the standard offset in hours, -5 in case of America/Denver  
       int standardOffset = dtz.getStandardOffset(oldDateTime.getMillis())/3600000;  
       // / calculate the dst offset in hours, -4 in case of America/Denver  
       int dstOffset = dtz.getOffset(oldDateTime.getMillis())/3600000;  
       // check if dst is enabled and adjust the date and time accordingly  
         newDateTime = oldDateTime.plusHours(dstOffset);  
         newDateTime = oldDateTime.plusHours(standardOffset);  
       // finally convert the new formatted date-time into a string  
       String formattedRawDate = newDateTime.toString("yyyyMMddHHmm");  

No comments: