Search code examples
javadatedatetimejodatimeutc

Date in UTC zone in Java using Joda-Time


I need to convert Joda-Time date/time to java.util.Date. I'm doing as follows.

DateTimeFormatter dateTimeFormatter=DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa");
DateTime dateTime = dateTimeFormatter.parseDateTime("2-Oct-2013 11:34:26 AM").withZone(DateTimeZone.UTC);

System.out.println(dateTime);

This displays date/time represented by UTC zone as expected. In this case, it is 2013-10-02T06:04:26.000Z

When this dateTime is converted to java.util.Date as follows,

System.out.println(dateTime.toDate());

it shows, Wed Oct 02 11:34:26 IST 2013. It should be in the UTC format.

Is there a way to represent a Date in UTC after converting it from Joda-Time?

I want a date to be stored into a database as represented by the UTC zone. org.joda.time.DateTime needs to be converted to java.util.Date (or java.sql.Timestamp) before inserting it to a database. How to overcome this situation?


Solution

  • A java.util.Date object per definition is always in UTC!
    (timestamp is the number of millis since 1.1.1970 UTC)

    But you have to set the timeZone to utc before time formating:

    TimeZone utc = TimeZone.getTimeZone("UTC")
    
    SimpleDateFormatter df = new SimpleDateFormatter (PATTERN);
    df.setTimeZone(utc);
    
    System.out.println(df.format(date));
    

    In your code you used the java.util.Date.toString() method which uses your system default TimeZone.