How to convert java.sql.timestamp to LocalDate (java8) java.time?
The smallest, most effective way to convert java.sql.Timestamp to LocalDate is to use toLocalDateTime() and toLocalDate():
This compact one-liner pulls out the date from a timestamp just like a hand in a magician's hat.
Accounting for time zone differences
Even though the approach above is quick and trouble-free, it turns a blind eye to time zones. The toLocalDateTime() method involves an underlying assumption of the system's default time zone. Should your application require compliance with a specific time zone, make sure this is handled directly:
This piece of code guarantees that there's zero ambiguity during the conversion process, and time zone uniformity is maintained throughout your application.
Tackling precision and accuracy losses
Bear in mind that java.sql.Timestamp comes with nanosecond precision, which sadly isn't retained when converted to LocalDate. If your use case revolves around minute time details, consider if truncating to a date-only format works for you.
Keeping a tab on common slip-ups
Dealing with dates and timings typically amount to tricky bugs unless you keep a sharp eye out:
-
Time zone inconsistencies: The question "Is the system's default time zone what you really intended?" should always linger. Unwittingly using
ZoneId.systemDefault()can lead to unpleasant surprises if your application shifts environments or the system time zone changes. -
Data loss: A
Timestampcan hold more than just a date. Converting toLocalDateinherently sheds time info; do this only when the loss isn't detrimental. -
Fly-by-conversions: During database interfacing, it’s routine for apps to convert between
java.sql.Timestampandjava.time. For accuracy, usejava.time.ZonedDateTimeorjava.time.OffsetDateTimeto encapsulate both date and time with a time zone offset.
Fine-tuning time zone settings
If you desire absolute precision, earmark a ZoneId during conversion. Here's how to convert a Timestamp to LocalDate in the UTC jurisdiction:
Or, utilize the system default time zone:
This way, the context is spelt out explicitly, bypassing any possible misinterpretations or assumptions.
Marching towards java.time
Java 8 introduced us to a hefty java.time API. It's a good practice to shift your application to use java.time types like Instant, LocalDate, and ZonedDateTime. Not only is their precision superior, they're also compatible beyond the older java.util.Date and java.sql.Timestamp. Making them immutable is the cherry on top, especially in a multithreaded environment.
Was this article helpful?