Skip to main content
Advertisement

10.1 Date & Time Introduction

Note: This guide is written based on Java 21.

To answer questions like "What is today's date?", "How many days are between these two dates?", or "Has it been 30 days since the payment?" in Java, you need dedicated classes specifically designed for handling dates and times.

In Java's history, handling dates and times is broadly split into two generations.

1. Legacy Generation: The Calendar & Date Classes

The java.util.Calendar and java.util.Date classes have existed since Java was first created. You will still frequently encounter them in old legacy codebases.

import java.util.Calendar;

Calendar cal = Calendar.getInstance();
System.out.println("Current Year: " + cal.get(Calendar.YEAR)); // e.g., 2026
System.out.println("Current Month: " + (cal.get(Calendar.MONTH) + 1)); // Warning! Months start at 0, so +1 is needed
System.out.println("Current Day: " + cal.get(Calendar.DAY_OF_MONTH));

Why do developers discourage their use? Calendar and Date suffer from fundamental design flaws, making them strongly discouraged in professional settings:

  • Months start from 0.(January = 0, December = 11 → a minefield for bugs!)
  • Objects are Mutable, causing bugs when shared across multiple places.
  • They are not thread-safe, making them dangerous in concurrent environments.

2. Modern Generation: The java.time Package (Java 8+)

The java.time package, revolutionarily introduced in Java 8, completely remedies all the flaws listed above. It is the current standard for all date and time operations in Java.

Core classes from the java.time package:

ClassPurpose
LocalDateDate only (year, month, day). No time component
LocalTimeTime only (hour, minute, second). No date component
LocalDateTimeBoth date AND time combined
ZonedDateTimeDate, time, AND timezone (e.g., Asia/Seoul) included
DurationInterval between two times (measured in seconds, milliseconds)
PeriodInterval between two dates (measured in years, months, days)
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;

// Get today's date
LocalDate today = LocalDate.now();
System.out.println("Today: " + today); // 2026-03-13

// Get the current time
LocalTime now = LocalTime.now();
System.out.println("Current Time: " + now); // 17:30:08.123

// Both date and time together
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Date + Time: " + dateTime); // 2026-03-13T17:30:08.123

// Specifying a particular date yourself
LocalDate birthday = LocalDate.of(1995, 6, 15); // Month starts from 1! Very intuitive.
System.out.println("Birthday: " + birthday); // 1995-06-15

The java.time package, especially LocalDate and LocalDateTime, are classes you will encounter extremely frequently throughout professional Java development. In the next chapter, we will master calculating date differences and converting formats (Formatting).

Advertisement