Issue
We have a requirement, where the date time data are stored in DB in UTC format. But the UI requirement is to show it in PST format.
So we need to manipulate the data while building the API data in Java Spring.
Data which is coming from DB is in this format: "2020-11-16T11:13:46"
[This is UTC]
I've tried below solution, but getting error.
private LocalDateTime convertUtcToPst(LocalDateTime timeStamp) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss" );
LocalDateTime ldt = LocalDateTime.parse(timeStamp, formatter);
ZoneId zoneId = ZoneId.of("America/Los_Angeles" );
ZonedDateTime zdt = ldt.atZone(zoneId );
return zdt;
}
Can someone please help me with the solution. If you look at the return statement, it also shows an error.
Solution
First add UTC to the timestamp,
then convert it
ZonedDateTime zoned = timestamp.atZone(ZoneId.of("UTC"));
ZonedDateTime converted = zoned.withZoneSameInstant(
ZoneId.of("America/Los_Angeles"));
apply toLocalDateTime()
to get a date-time without the zone information.
Note: formaters are used to convert from object (~binary) to string and vice-versa, that is, format()
(similar toString()
) is used to create a String
representing that object; parse()
is the reverse, tries to create an object from a given String
.
Answered By - user15244370