1

I get timestamps as a String in a stream and they are of the format "2016-12-08 05:44:48 <timezone like IST, UTC>" and "2016-12-08 05:44:48 <timezone like +0000>"

I want to convert the string to java.sql.Timestamp so I wrote a function as follows

private static Timestamp convertToTimestamp(String s) throws ParseException{
    String dateFormat = new String("yyyy-MM-dd hh:mm:ss z");
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    Date d = sdf.parse(s);
    return new Timestamp(d.getTime());
}

When I run

Timestamp t = convertToTimestamp("2016-12-08 05:44:48 UTC");
System.out.println(t);

The output is 2016-12-08 11:14:48.0

It is automatically converting into IST (Probably my JVM default). How to make the change so that the output time not changed to IST and is same as input?

Sashank
  • 590
  • 7
  • 22

2 Answers2

2

Java's java.util.Date and java.sql.Timestamp do not store timezone.

They always track time in UTC.

When parsing a date string that includes a timezone, the string is correctly parsed and adjusted from the given timezone to UTC.

When parsing a date string without timezone, the string is parsed in the JVM's default timezoneand converted to UTC, unless another timezone has been explicitly given to the date parser (commonly SimpleDateFormat).

When displaying (aka formatting) a Date/Timestamp, it will be shown in the JVM's default timezone, unless otherwise specified.

The Date/Timestamp objects cannot store a timezone, so they cannot remember what the original timezone was.

If you need that, use Java 8's ZonedDateTime.

Andreas
  • 154,647
  • 11
  • 152
  • 247
1

You have to ignore the time-zone when parsing the date

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Aimee Borda
  • 842
  • 2
  • 11
  • 22