Reputation: 1907
Given a date/time String in this format:
2021-12-05 21:10:00 UTC
, how do I parse it into a Java DateTime object?
It seems to require a formatter string such as uuuu-MM-dd HH:mm:ss
, but what do I do with the "UTC" and how do I make sure the Java object specifies UTC?
Upvotes: 2
Views: 227
Reputation: 38424
The thing you're missing is a timezone specifier, eg. z
.
// first
private static final DateTimeFormatter DATETIME_PARSER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss z");
//then
String dateString = "2021-12-05 21:10:00 UTC";
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, DATETIME_PARSER);
This correctly produces the date-time object you need.
That said, it's unclear whether you need z
(time-zone name), VV
(time-zone ID), or v
(generic time-zone name) as they all mean something slightly different and all will work with "UTC". See the documentation for the supported formatting.
EDIT:
The data comes from an environmental sensor whose location is known, and the only thing that matters is that the date/time value is UTC.
In that case it does not matter, just use z
.
As a commenter rightfully suggested, you might want to use Instant
instead of ZonedDateTime
if all you care about is the point on the timeline and you do not care about the timezone the event originated from:
Instant instant = Instant.from(DATETIME_PARSER.parse(dateString));
Upvotes: 8