Working with Dates in Java: java.time and Joda-Time

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is it and why is it needed?

Working with dates and time is one of the most common tasks in Java programming. The standard library java.time (introduced in Java 8) provides a powerful and intuitive API for handling dates, time, time zones, and periods. Before Java 8, developers often used the third-party library Joda-Time, which became the prototype for java.time. Both libraries solve the problems of the old java.util.Date and java.util.Calendar: thread safety, object immutability, and convenient formatting methods.

How to install?

java.time is built into Java 8 and newer — no installation is required. For Joda-Time, add the dependency in Maven:

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.5</version>
</dependency>

For Gradle: implementation 'joda-time:joda-time:2.12.5'.

Main features

  • LocalDate, LocalTime, LocalDateTime — working with date/time without a time zone.
  • ZonedDateTime, OffsetDateTime — handling time zones.
  • Period, Duration — difference between dates and time.
  • DateTimeFormatter — flexible formatting and parsing.
  • Instant — a moment in time in UTC.

Java code example

import java.time.*;
import java.time.format.DateTimeFormatter;

public class DateExample {
public static void main(String[] args) {
// Current date
LocalDate today = LocalDate.now();
System.out.println("Today: " + today);

// Creating a specific date
LocalDate specificDate = LocalDate.of(2025, Month.MARCH, 15);
System.out.println("Specific date: " + specificDate);

// Difference between dates
Period period = Period.between(specificDate, today);
System.out.println("Difference: " + period.getYears() + " years, " + period.getMonths() + " months, " + period.getDays() + " days");

// Formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String formatted = today.format(formatter);
System.out.println("Formatted: " + formatted);

// Parsing a string
LocalDate parsed = LocalDate.parse("01.01.2024", formatter);
System.out.println("Parsed: " + parsed);

// Working with time and zones
ZonedDateTime zoned = ZonedDateTime.now(ZoneId.of("Europe/Moscow"));
System.out.println("Moscow time: " + zoned);
}
}

When to use

java.time is the primary choice for all new projects on Java 8+. Use it for: calculating age, deadlines, logs with timestamps, task schedulers, working with calendars and time zones. Joda-Time is useful for supporting legacy projects or if additional features are needed, such as Interval or MutableDateTime. Both libraries significantly simplify code compared to the outdated Calendar.

Recommendations