Search code examples
javadatetimejodatime

converting one time zone to another using joda time


i have made a function to convert from one time zone to another by using joda time but the function is not accepting the date
i have passed the following parameters to this function "Asia/Kolkata", "UTC", "12-Dec-2014 12:30". It is throwing the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "12-Dec-2014 12:32" is malformed at "-Dec-2014 12:32"
at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:752)
at org.joda.time.convert.StringConverter.getInstantMillis(StringConverter.java:65)
at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:150)
at org.joda.time.DateTime.<init>(DateTime.java:265)
at Dtime.convertTimeZones(Dtime.java:17)
at Dtime.main(Dtime.java:9) 

Here is the code:

public static String convertTimeZones( String fromTimeZoneString, 
    String toTimeZoneString, String fromDateTime) {
         DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString);
         DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString);
         DateTime dateTime = new DateTime(fromDateTime, fromTimeZone);

         DateTimeFormatter outputFormatter = 
             DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm").withZone(toTimeZone);
         return outputFormatter.print(dateTime);
}

DST (day light savings )
i am passing the parameters as ("America/Denver","GMT","09-Mar-2014 02:00")on this date the DST will start
for denver
Sunday, 9 March 2014, 02:00:00 clocks are turned forward 1 hour to
Sunday, 9 March 2014, 03:00:00 local daylight time instead
but it is throwing the exception
Exception

Exception in thread "main" java.lang.IllegalArgumentException: Cannot parse "09-Mar-2014 02:00": Illegal instant due to time zone offset transition (America/Denver)
    at org.joda.time.format.DateTimeParserBucket.computeMillis(DateTimeParserBucket.java:390)
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:849)
    at timeZone.convertTimeZones(timeZone.java:23)
    at timeZone.main(timeZone.java:14)

Solution

  • You need to parse your date with an inputFormatter (like the outputFormatter you've already defined). Something like this

    DateTimeFormatter inputFormatter = DateTimeFormat.forPattern(
        "dd-MMM-yyyy HH:mm").withZone(fromTimeZone);
    DateTime dateTime = inputFormatter.parseDateTime(fromDateTime);
    

    Which I tested, and it outputs

    12-Dec-2014 07:00