convert string to date without changing timezone in the string using java

Viewed 289

I have a string with timezone included like 2020-11-12T12:00:00-0800. When I converting into to date in the JAVA time zone automatically changing to IST, can someone help with this? thanks in advance.

String s = '2020-11-12T12:00:00-0800'
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
date = format.parse(s);
2 Answers

Just omit the timezone format from the end of the String (letter Z). For example, this will print Thu Nov 12 06:30:00 CET 2020

String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
var date = format.parse(s);
System.out.println(date);

But if I add the letter Z at the end, it will interpret the given timezone and change time to my local timezone, when printed. So this will print Thu Nov 12 15:30:00 CET 2020

String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
var date = format.parse(s);
System.out.println(date);

More about the patterns can be found in the JavaDoc of SimpleDateFormat.

To preserve the time zone and also moving to the new (since Java 8) api java.time you can use ZonedDateTime

ZonedDateTime date = ZonedDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));

The result then is

String s = "2020-11-12T12:00:00-0800";
ZonedDateTime date = ZonedDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
System.out.println(date);

2020-11-12T12:00-08:00

Related