0

When converting a string to a Joda DateTime in UTC based on a user's timezone and then converting it to a java.sql.Timestamp, it changes back to eastern time.

DateTimeZone usersTimezone = DateTimeZone.forID("America/New_York");
String DATE_FORMAT = "MM/dd/yyyy hh:mm aa";
DateTimeFormatter DATETIME_FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT);
DateTime date = DATETIME_FORMATTER.withZone(usersTimezone).parseDateTime("03/06/2016 5:30 AM");
DateTime utcDateTime = date.toDateTime(DateTimeZone.UTC);

java.sql.Timestamp utcTimestamp = new java.sql.Timestamp(utcDateTime.getMillis());

System.out.println(" UTC DATETIME: " + utcDateTime);
System.out.println("UTC TIMESTAMP: " + utcTimestamp);

Prints the following:

UTC DATETIME: 2016-03-06T10:30:00.000Z
UTC TIMESTAMP: 2016-03-06 05:30:00.0

Why does the timestamp convert back to Eastern time zone? I want to enter it in the database as a timestamp in UTC?

Note: Changing my server's timezone to UTC makes no difference.

techraf
  • 64,883
  • 27
  • 193
  • 198
Abu Sulaiman
  • 1,477
  • 2
  • 18
  • 32

1 Answers1

1

java.sql.Timestamp.toString() will print the timestamp in the current timezone, not UTC.

The value is correct, you're simply printing it wrong.

That internal value of Timestamp is in UTC, like all the other java.util.Date classes.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • So if I execute stmt.setTimestamp(1,utcTimestamp); It will be correctly stored in mySql database in UTC? Why doesn't it show as UTC when I changed my server time to UTC? – Abu Sulaiman Mar 06 '16 at 00:08
  • @AbuSulaiman The answer to that question depends on the type of database, the data type of the column, and various settings. – Andreas Mar 06 '16 at 00:29
  • It seems that the easiest way to deal with timezones in my case is to convert user datetime selections to my local timezone to store in my database and convert them back when displaying for the user. Thanks. – Abu Sulaiman Mar 06 '16 at 04:00
  • I totally get it now. It doesn't matter what timezone it is in when I convert it to timestamp because it is the SAME time everywhere UTC regardless. Why was this so confusing to me? – Abu Sulaiman Mar 06 '16 at 11:20