I need to convert the timestamp to UTC. Timestamp has the MST timezone, which is specified in the timestamp
Examples of observed conversions:
- 2023-03-20 08:53:19 MST -> 2023-03-20T14:53:19 (-6)
- 2023-01-20 08:53:19 MST -> 2023-01-20T15:53:19 (-7)
static DateTimeFormatter EVENT_TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzz");
static LocalDateTime timestampConverter(String timestamp) {
return ZonedDateTime.parse(timestamp, EVENT_TIMESTAMP_FORMATTER)
.withZoneSameInstant(ZoneOffset.UTC)
.toLocalDateTime();
}
MDT offset from UTC is -6:00 hours
MST offset from UTC is -7:00 hours
Problem: Java conversion treats MST as MDT which observe daylight saving
For example JS library doesn't have this problem:
console.log(new Date("2023-03-20 08:53:19 MST").toUTCString()); // Mon, 20 Mar 2023 15:53:19 GMT
Question: Why logic is different from the standard behavior ?
First and foremost, let's define the error in the provided snippet.
I realize that the snippet above treats the MST timezone as MDT and does not take daylight saving into account. I hope you understand that.
Now, let's fix the issue, you can use the ZoneId class to specify the time zone with daylight saving. Use this updated version of the timestampConverter method and that should work for both MST and MDT:
This should fix the challenge you are currently going through! And if you need more clarification... Don't hesitate. Happy Coding!