Timestamp is one of a few legacy date-time objects in Java.
In this tutorial, we'll see how to parse from a String value to a Timestamp object and how to format a Timestamp object to a String.
And since Timestamp relies on a Java-proprietary format, we'll see how to effectively adapt.
2. Parse a String to a Timestamp
2.1. Standard Format
The simplest way to parse a String to a Timestamp is its valueOf method:
And when our String is in JDBC timestamp format – yyyy-m[m]-d[d] hh:mm:ss[.f…] – then it's pretty simple.
We can interpret that pattern like this:
|yyyy||Represents the year, and it's mandatory to have four digits for it.||2018|
|m[m]||For the month component, we must have either one or two digits (from 1 to 12).||1, 11|
|d[d]||For the day of month value, we must have either one or two digits (from 1 to 31).||7, 12|
|hh||Stands for the hour of the day, with allowed values from 0 to 23.||01, 16|
|mm||Stands for minutes of the hour, with allowed values from 0 to 59.||02, 45|
|ss||Stands for seconds in the minute, with allowed values from 0 to 59.||03, 52|
|[.f…]||Represents optional fractions of a second, can be up to nanoseconds precision so the allowed values are from 0 to 999999999.||12, 1567, 123456789|
2.2. Alternative Formats
Now, if it isn't in JDBC timestamp format, then luckily, valueOf also takes a LocalDateTime instance.
This means we can take a date in any format, we just need to first convert it into a LocalDateTime:
String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS"; String timestampAsString = "Nov 12, 2018 13:02:56.12345678"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
And then we can use valueOf we did before:
Timestamp timestamp = Timestamp.valueOf(localDateTime); assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
Note in passing that, unlike a Date object, a Timestamp object is capable of storing fractions of a second.
3. Format a Timestamp as a String
To format a Timestamp, we'll have the same challenge since it's default format is the proprietary JDBC timestamp format:
assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
But, again, using an intermediary conversion, we can format the resulting String to a different date and time pattern, like the ISO-8601 standard:
Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789"); DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; String timestampAsString = formatter.format(timestamp.toLocalDateTime()); assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
In this article, we saw how to convert between String and Timestamp objects in Java. Also, we saw how to use LocalDateTime conversion as an intermediary step in order to convert to, and from, different date and time patterns.
And make sure to find all of these examples and snippets over on GitHub.