I'm trying to format the incoming timestamp in my spring boot app, but the code that I wrote is changing the timezone of the incoming timestamp. It is adding 5:30 hrs on its own which I don't want.
Here is my snippet:
String startTime = searchParams.getDeploymentStartDate();
System.out.println("startTime from req body in utc:"+startTime);
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd' HH:mm:ss"
, Locale.ENGLISH).ISO_OFFSET_DATE_TIME;
Date startDate = Date.from(ZonedDateTime.parse(startTime, targetFormatter).toInstant());
System.out.println("startDate converted to desired format in IST:"+startDate);
Actual output:
startTime from req body in utc:2023-03-22T11:27:04Z
startDate converted to desired format in IST:Wed Mar 22 16:57:04 IST 2023
Desired output:
startTime from req body in utc:2023-03-22T11:27:04Z
startDate converted to desired format in IST:Wed Mar 22 11:27:04 IST 2023
Please help me find a way to convert the format without converting timezone.
Please don't use
java.util.Dateas it's poorly designed and may be deprecated in future.Instead use
java.time.LocalDateTimeorjava.time.ZonedDateTime.Update:
You have to use
ZonedDateTime.withZoneSameLocal(ZoneId zone)if you want to keep the same time with the change in timezone only.From ZonedDateTime.withZoneSameLocal(ZoneId zone) JDK 8 doc :
So, update the code (without using
java.util.Date) to this:Output:
Note: If you want the timestamp in a different timezone, then just pass that timezone in
ZoneId.of(...)I'm providing a list of ZoneIds from the official doc that are supported :