1

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);
0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Oresztesz!, Yes, it's changing to my timezone.
You're welcome. If it works for you then don't forget to accept the answer: stackoverflow.com/help/someone-answers
1

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

1 Comment

Thank you, Joakim Danielson!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.