Explain Codes LogoExplain Codes Logo

How to get the current date/time in Java

java
time-zone-handling
java-time-api
date-and-time
Nikita BarsukovbyNikita Barsukov·Nov 5, 2024
TLDR

Quickly grab the current date and time in Java 8 and onwards utilizing LocalDateTime.now(). Here's how to do it in a snap:

import java.time.LocalDateTime; LocalDateTime now = LocalDateTime.now(); System.out.println(now); // Prints the date and time as captured in your JVM

For time zone specific date and time, dial in ZonedDateTime.now(). It's like dialling an international friend - remember the time difference!

Time zone handling

Broadening your horizons? Here's how to get date-time specifics for different zones:

import java.time.ZonedDateTime; import java.time.ZoneId; ZonedDateTime nowInParis = ZonedDateTime.now(ZoneId.of("Europe/Paris")); System.out.println(nowInParis); // Voila! You are virtually in Paris.

Tracking precise moments

When every millisecond counts, Instant.now() offers timestamp precision. It's the Java equivalent of a high-speed camera:

import java.time.Instant; Instant timestamp = Instant.now(); System.out.println(timestamp); // Laser accurate timestamp in UTC. No kidding!

Count from the epoch

For those retro folks who prefer counting seconds from the epoch, System.currentTimeMillis() is Java's built-in time machine:

long millis = System.currentTimeMillis(); System.out.println(millis); // Prints the milliseconds from the epoch. Cool, right?

Farewell to the old

Embrace java.time API when migrating from Joda-Time. java.time format offers modern API support with smoother maintenance and thread safety:

import java.time.format.DateTimeFormatter; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"); String formattedNow = now.format(formatter); System.out.println(formattedNow); // Out with the old, in with the new.

Practical examples

Need a custom formatted timestamp for file naming? DateTimeFormatter does the needful with a pattern of your choice:

String fileNameTimestamp = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")); String fileName = "backup_" + fileNameTimestamp + ".zip"; // There's your file. Now zip it before it unformats!

Database integration

Applications dealing with databases need Java's Database Connectivity. Luckily, JDBC 4.2 is here to save your day with direct java.time type operations:

PreparedStatement pstmt = con.prepareStatement("INSERT INTO events (occurrence) VALUES (?)"); pstmt.setObject(1, LocalDateTime.now()); pstmt.executeUpdate(); // Who knew inserting date and time could be this fun?

The classics and the modern

For sturdy soldiers on Java 6 and 7, ThreeTen-Backport comes to your aid. For Android knights, ThreeTenABP ensures you enjoy the fruits of modern date and time API.

Best practices worth adopting

  • Ensure to set time zones explicitly with ZoneId to say goodbye to disruptions.
  • For capturing the date with correct time zone, use LocalDate.now(ZoneId).
  • The java.time.Clock is your accomplice for testable, alternative time sources. Mock it, tweak it, test it!