How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
In Java, snag the current time including milliseconds with this piece of code:
Understanding the Concepts
Working with Time Zones
When universal time is your jam, use ZonedDateTime
to specify a time zone for your current time:
For the Legacy Code Aficionados
Stuck in a pre-Java 8 world? SimpleDateFormat
comes to your rescue:
Just remember, it's not thread-safe. So keep it locked down when multiple threads are involved!
When Instant becomes eternity
The Instant
class represents a moment on the timeline. Format this bad boy like this:
Don't sweat the small stuff! Instant
truncates to the nearest millisecond during formatting.
Embrace the Future with Java 8 (and Beyond)
Java 8's java.time
eases date-time operations with immutable and thread-safe classes like DateTimeFormatter
and LocalDateTime
. Like regular shampoo and conditioner - in one bottle!
Tailoring your Time Display
Jazz up your time representation by using DateTimeFormatter.ISO_LOCAL_DATE_TIME
:
Pitfalls in formatting time
When handling date and time around the globe, locale-sensitive data isn't something to ignore. Specify your Locale
when creating your DateTimeFormatter
:
Was this article helpful?