Pergunta

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?

Foi útil?

Solução 2

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top