3
\$\begingroup\$

I've been struggling to get to grips with Joda-Time, but feel that I've finnaly managed to get a grip on some of the functionality that I need.

I have written a function that will convert a DateTime from one timezone to another. I've not done any unit testing on it (but have done my own testing), but would appreciate comments on if it could be improved. The code is in native Java.

import org.joda.time.*;
import org.joda.time.format.*;
public class testing {

    /**
     * @param args
     */
    public static void main(String[] args) {

public string ConvertTimeZones(String sFromTimeZone, String sToTimeZone, String sFromDateTime){
        DateTimeZone oFromZone       = DateTimeZone.forID(sFromTimeZone);
        DateTimeZone oToZone         = DateTimeZone.forID(sToTimeZone);

        DateTime oDateTime           = new DateTime(sFromDateTime);
        DateTime oFromDateTime       = oDateTime.withZoneRetainFields(oFromZone);

        DateTime oToDateTime         = new DateTime(oFromDateTime).withZone(oToZone);

        DateTimeFormatter oFormatter = new DateTimeFormat.forPattern("yyyy-MM-dd'T'H:mm:ss.SSSZ");
        DateTimeFormatter2           = new DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss");

        DateTime oNewDate            = oFormatter.withOffsetParsed().parseDateTime(oToDateTime.toString());

        return oFormatter2.withZone(oToZone).print(oNewDate.getMillis());
   }
}
}

The arguments:

sFromTimeZone = UTC
sToTimeZone = Europe/London
sFromDateTime = 2012-05-08 18:00:00

should produce a return of

2012-05-08 19:00:00
\$\endgroup\$
8
\$\begingroup\$
  1. First of all, currently it does not compile. You should fix that, non-working codes are off-topic here.

  2. According to the Code Conventions for the Java Programming Language, method names should start with lowercase letters and class names should start with uppercase letters. ConvertTimeZones should be convertTimeZones.

  3. The o prefix is unnecessary for every variable.

  4. You could omit lots of intermediate objects. Here is a simplified version:

    public static String convertTimeZones(final String fromTimeZoneString, 
            final String toTimeZoneString, final String fromDateTime) {
        final DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString);
        final DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString);
        final DateTime dateTime = new DateTime(fromDateTime, fromTimeZone);
    
        final DateTimeFormatter outputFormatter 
            = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss").withZone(toTimeZone);
        return outputFormatter.print(dateTime);
    }
    
  5. Here are a few unit tests:

    import static ...TimeZoneConverter.convertTimeZones;
    import static org.junit.Assert.assertEquals;
    
    import java.util.Arrays;
    import java.util.Collection;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    import org.junit.runners.Parameterized.Parameters;
    
    @RunWith(value = Parameterized.class)
    public class TimeZoneConverterTest {
    
        private final String expectedDatetime;
        private final String fromTimezone;
        private final String toTimezone;
        private final String inputDatetime;
    
        public TimeZoneConverterTest(final String expectedDatetime, 
                final String fromTimezone, final String toTimezone,
                final String inputDatetime) {
            this.expectedDatetime = expectedDatetime;
            this.fromTimezone = fromTimezone;
            this.toTimezone = toTimezone;
            this.inputDatetime = inputDatetime;
        }
    
        @Parameters
        public static Collection<Object[]> data() {
            final Object[][] data = new Object[][] {
                { "2012-05-08 19:00:00", 
                    "UTC", "Europe/London", "2012-05-08T18:00:00" },
                { "2012-05-08 17:00:00", 
                    "Europe/London", "UTC", "2012-05-08T18:00:00" },
                { "2012-05-08 20:00:00", 
                    "UTC", "CET", "2012-05-08T18:00:00" },
                { "2012-05-08 19:00:00", 
                    "America/Tijuana", "CET", "2012-05-08T10:00:00" },
                { "2012-11-08 21:00:00", 
                    "Europe/London", "Asia/Dubai", "2012-11-08T17:00:00" },
                { "2012-11-19 2:00:00", 
                    "Europe/London", "Asia/Tokyo", "2012-11-18T17:00:00" } };
            return Arrays.asList(data);
        }
    
        @Test
        public void test() {
            assertEquals(expectedDatetime, 
                convertTimeZones(fromTimezone, toTimezone, inputDatetime));
        }
    }
    
\$\endgroup\$
  • \$\begingroup\$ Hi. I am getting exception: java.lang.IllegalArgumentException: Invalid format: "2015-03-25 19:38:56" is malformed at " 19:38:56" at org.joda.time.format.DateTimeParserBucket.doParseMillis(DateTimeParserBucket.java:187) at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:780) at org.joda.time.convert.StringConverter.getInstantMillis(StringConverter.java:65) at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:154) at org.joda.time.DateTime.<init>(DateTime.java:281) \$\endgroup\$ – Shajeel Afzal Mar 25 '15 at 20:09
  • \$\begingroup\$ @ShajeelAfzal: It seems to me that the code above still works well on my machine with Joda-Time 2.1. I guess it is quite old now so I've tried with 2.7 and it works as well. My guess it that you probably missed the T (it should be 2015-03-25T19:38:56). If it's not help could you ask a question with some code and context information on Stack Overflow and drop me a link here? \$\endgroup\$ – palacsint Mar 25 '15 at 20:47
0
\$\begingroup\$

I was also struggling to convert a DateTime from a specified DateTimeZone to another DateTimeZone. Here is how I managed it :

    String myDate; // To initialise with the string you want to parse

    DateTimeFormatter formatter = DateTimeFormat.forPattern(myPattern);
    // Here, you can specify the original specified DateTimeZone of your String
    formatter = formatter.withZone(originalDateTimeZone);
    // Then, parse your String
    DateTime originalDateTime = formatter.parseDateTime(myDate);

    // Specify the new DateTimeZone and construct the new DateTime
    DateTime newDateTime = dateTime.toDateTime(newDateTimeZone);
\$\endgroup\$
  • 1
    \$\begingroup\$ You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read How do I write a good answer?, which states: "Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review" \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Mar 19 '18 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.