Reputation: 251
How to convert Timestamp
to LocalDateTime
preserving the time zone?
I tried using TimestampObject.toLocalDateTime().toLocalDate()
however this does not preserve time zone.
Upvotes: 1
Views: 5188
Reputation: 86281
You should really use the proper datatype for storing your timestamp in your database. Depending on your exact requirements and the capabilities of your RDBMS this could be for example timestamp with time zone
or datetimeoffset
for MS. Then from Java store OffsetDateTime
or just Instant
objects into the database and retrieve the same type back. OffsetDateTime
is called that because it holds an offset in it in addition to date and time-of-day. Its methods toLocalDateTime
and toLocalDate
preserve the offset in the sense that the time and the date they give agree with the original offset. Neither LocalDate
nor LocalDateTime
can hold an offset or time zone themselves. Avoid the long outdated java.sql.Timestamp
class if you can.
Your string includes -0800
, an offset from UTC, and then UTC
, which usually would mean offset 0 from UTC, but in this case may mean that the former offset was from UTC. I hope you know because I don’t. An offset is not the same as a time zone: a time zone contains all historic and known future changes in offset for the location it represents.
Assuming that your database already contains strings (for example varchar
), you may get the date, time and offset from them like this:
DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
.appendPattern("d-MMM-uuuu h:mm ")
.parseCaseInsensitive()
.appendPattern("a")
.parseCaseSensitive()
.appendPattern(" xx 'UTC'")
.toFormatter(Locale.ROOT);
String timestampString = "30-Jan-2018 5:17 pm -0800 UTC someText";
ParsePosition pos = new ParsePosition(0);
OffsetDateTime dateTime
= OffsetDateTime.from(timestampFormatter.parse(timestampString, pos));
LocalDate date = dateTime.toLocalDate();
I am taking into account that the string contains am
or pm
in lowercase, where Java would normally expect uppercase, by parsing that bit case insensitively, and I check that the text UTC
is there, but don’t use it for anything. The snippet produces an OffsetDateTime
of 2018-01-30T17:17-08:00
and next a LocalDate
of 2018-01-30
.
Upvotes: 2