2

The following segment of code formats and converts a date to the UTC zone using the Joda-Time API.

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

It displays the following date exactly as expected.

2013-10-15T06:04:26.000Z

But when this date is converted to java.sql.Timestamp like so,

System.out.println(new Timestamp(dateTime.getMillis()));

it displays the following date.

2013-10-15 11:34:26.0

This means the same date/time as given. The time zone UTC appeared to be ignored.


How to get Timestamp to correctly convert a date to UTC?

Tiny
  • 27,221
  • 105
  • 339
  • 599
  • 2
    It's not that `TimeStamp` is ignoring the time zone, I believe it's using the local time zone for its `toString` method - needs to be validated. Remember, things like `TimeStamp` and `Date` aren't meant to be used for display the results, that's what formatters are for... – MadProgrammer Oct 15 '13 at 04:02
  • Is there a way to tell `Timestamp` to use the UTC zone? It is needed in a [converter](http://stackoverflow.com/q/19371138/1391249). I initially believed that there was something wrong with this converter. – Tiny Oct 15 '13 at 04:46
  • AFAIK `TimeStamp` is simply a container for the number of milliseconds since the epoch, it doesn't carry any time zone details with it per say – MadProgrammer Oct 15 '13 at 04:51

2 Answers2

1

Java Timestamp.toString() outputs in UTC (although it doesn't say as much in the javadoc, the source uses no TimeZone info). Since your original date/time is in UTC, you will see the exact same output.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
0

Despite the fact that the println() method implicitly uses the Timestamp#toString() method while displaying it on the console which in turn uses the current JVM timezone to display date-time (the JVM timezone is the system timezone by default which the operating system uses), the original intention of the question was to persist new Timestamp(dateTime.getMillis()) to MySQL database with the UTC zone which will not happen for the reasons mentioned in the following related answers.

Community
  • 1
  • 1
Tiny
  • 27,221
  • 105
  • 339
  • 599