I have already upvoted Bryan’s answer exactly because it includes and recommends the java.time
solution. I need to add a few thoughts, though.
Your code, reviloSlater, throws away the time zone information (more precsely, zone offset information), I’m not sure I would dare do that from the outset. With java.time
classes it’s more natural to include it, and it’s easy to discard at a later point when we are sure we don’t need it.
To parse with offset:
OffsetDateTime loginOdt = OffsetDateTime.parse("2017-05-16 06:24:36-0700",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ"));
To drop the time zone offset information
LocalDateTime loginLdt = loginOdt.toLocalDateTime();
A LocalDateTime
is a date and a time without any time zone or offset information. In this case of course we get
2017-05-16T06:24:36
Bryan’s java.time
code too uses the time zone offset information from the string. Edit: after Bryan’s edit that code now works and gives us:
2017-05-16T13:24:36Z
This is the same point in time (Instant.toString()
prints the time in UTC). Another way is, with the OffsetDateTime
from before we can just do
Instant login = loginOdt.toInstant();
java.time
is loaded with possibilities.