Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get the current date and time

Short answer

Classes from the java.time package return the current values with now():

void main() {
    IO.println(LocalDate.now());
    IO.println(LocalTime.now());
    IO.println(LocalDateTime.now());
}

Output:

2026-10-04
06:22:22.014925300
2026-10-04T06:22:22.015926700

You will see your own current time. LocalDate is a date only, LocalTime a time only, and LocalDateTime both, without a time zone.

In a specific time zone

now() uses the computer's time zone. Pass a ZoneId to get the time somewhere else:

void main() {
    IO.println(ZonedDateTime.now(ZoneId.of("Europe/Berlin")));
    IO.println(ZonedDateTime.now(ZoneId.of("Asia/Tokyo")));
}

Output:

2026-10-04T08:22:21.174894100+02:00[Europe/Berlin]
2026-10-04T15:22:21.212486100+09:00[Asia/Tokyo]

A point in time

Instant is a moment on the timeline in UTC. It is used for logs and for storing in a database:

void main() {
    Instant now = Instant.now();
 
    IO.println(now);
    IO.println(now.toEpochMilli());
}

Output:

2026-10-04T06:22:22.378958700Z
1791094942378

Individual parts

You can get the year, month, day and day of week from a date:

void main() {
    LocalDate today = LocalDate.now();
    IO.println(today.getYear() + " " + today.getMonth() + " " + today.getDayOfMonth() + " " + today.getDayOfWeek());
}

Output:

2026 OCTOBER 4 SUNDAY

Common mistake

Using the old Date and Calendar classes. They are mutable, months in Calendar are numbered from zero, and Date.toString() prints an awkward format. In new code use java.time, and only meet Date at the boundary with old libraries — date.toInstant() converts it to the new API.

Functions used in this recipe

  • LocalDate.now() — Returns today's date from the computer's clock and time zone.
  • LocalDateTime — A date and time without a time zone — for example, a meeting in a calendar.
  • ZonedDateTime — A date and time in a specific time zone — with daylight saving time taken into account.
  • Instant — An exact moment on the UTC timeline — for logs, timestamps and measurements.

Thanks for reading!

Donate to the site — we work hard for you.