Convert LocalDate to LocalDateTime or java.sql.Timestamp
To transform a LocalDate
to a LocalDateTime
at midnight (00:00), use atStartOfDay()
method and convert it to Timestamp
with valueOf()
:
Or, here's how to directly convert LocalDate
to Timestamp
, also at midnight:
Both of these give a Timestamp
for the start of the day.
Embracing Time zones when converting
When the time zone matters, we bring in the ZonedDateTime
:
By using ZonedDateTime
, you're ensuring the time zone isn't lost in translation.
JPA and JDBC 4.2+ compatibility
If you're a JPA user, implement the AttributeConverter
to tackle Java 8's time types:
With JDBC 4.2+ drivers, it's a smooth sail as they can talk java.time
directly with your database.
A Fraction of seconds does matter
If you're not mindful, converting between LocalDate
, LocalDateTime
, and Timestamp
could chop off fractional seconds:
Truncation is a real problem, but with this, we avoid losing those precious nanoseconds.
Capturing current moment using Instant
To capture the current moment in UTC, java.time.Instant
is at your service:
The Instant
class lends a hand to precision and makes moment capturing seem like child's play.
Proper DateTime formatting
Get yourself a custom string representation of date-time with a DateTimeFormatter
that dances to your tune:
Java 8 time types and database compatibility
It's essential to remember your database and its version when dealing with Java 8's time types:
- Postgres (version 9.4.1208+) and
- HSQLDB (version 2.4.0+)
both natively support Java 8 Time API.
Quick and efficient Timestamp creation
You're one line away from a Timestamp
with the current date & time:
Key takeaways while converting
- Consider the time zone because not everywhere is 'right here'.
- With JPA and JDBC (4.2+), you're playing with the big boys now.
- Fractional seconds do count! Don't let them disappear.
- Go from zero to hero real quick with
java.time.Instant
. - Remember to wear the right
DateTimeFormatter
.
Was this article helpful?