Skip to content

Java Date and Time

Before Java 8, handling dates and times mainly relied on java.util.Date and java.util.Calendar classes, which had design flaws, were not thread-safe, and had a confusing API. Starting from Java 8, a completely new java.time package was introduced, providing immutable, thread-safe, and clearly designed APIs, which is the standard way to handle dates and times in modern Java development.

Core Classes in the java.time Package

  • LocalDate: Represents a date without a time zone (year-month-day). Example: 2024-07-25.
  • LocalTime: Represents a time without a time zone (hour:minute:second.nanosecond). Example: 15:30:00.
  • LocalDateTime: Represents a combination of date and time without a time zone. Example: 2024-07-25T15:30:00.
  • ZonedDateTime: Represents a date and time with a time zone. This is the preferred choice when dealing with scenarios that require time zone conversions.
  • Instant: Represents an instantaneous point on the timeline (timestamp), typically used for time recording between machines, internally based on UTC time zone.
  • DateTimeFormatter: Used to format and parse date-time objects.

Creating Date and Time Objects

Getting the current date and time is very simple.

java
import java.time.*;

public class DateTimeCreation {
    public static void main(String[] args) {
        // Get current date
        LocalDate today = LocalDate.now();
        System.out.println("Today's date: " + today);

        // Get current time
        LocalTime now = LocalTime.now();
        System.out.println("Current time: " + now);

        // Get current date and time
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("Current date and time: " + currentDateTime);

        // Get current date and time with time zone
        ZonedDateTime zonedNow = ZonedDateTime.now();
        System.out.println("Current time with time zone: " + zonedNow);
    }
}

You can also use the of() method to create specific dates and times.

java
// Create a specific date: January 1, 2025
LocalDate specificDate = LocalDate.of(2025, 1, 1);

// Create a specific time: 10:15:30
LocalTime specificTime = LocalTime.of(10, 15, 30);

// Create a specific date-time
LocalDateTime specificDateTime = LocalDateTime.of(specificDate, specificTime);
System.out.println("Specific date-time: " + specificDateTime);

Manipulating Date and Time

All objects in the java.time API are immutable, and any modification operation returns a new instance.

java
LocalDate today = LocalDate.now();

// Addition
LocalDate nextWeek = today.plusWeeks(1);
LocalDate tomorrow = today.plusDays(1);

// Subtraction
LocalDate yesterday = today.minusDays(1);

// Modify a specific field
LocalDate firstDayOfMonth = today.withDayOfMonth(1);

System.out.println("Tomorrow is: " + tomorrow);
System.out.println("First day of this month is: " + firstDayOfMonth);

Getting Date-Time Information

You can easily extract the parts you need from date-time objects.

java
LocalDateTime now = LocalDateTime.now();

int year = now.getYear();
Month month = now.getMonth(); // Returns a Month enum
int day = now.getDayOfMonth();
DayOfWeek dayOfWeek = now.getDayOfWeek(); // Returns a DayOfWeek enum

System.out.println("Year: " + year);
System.out.println("Month: " + month.getValue()); // Get the numeric value of the month
System.out.println("Today is: " + dayOfWeek);

Formatting and Parsing

DateTimeFormatter is the core tool for formatting and parsing date-time.

java
import java.time.format.DateTimeFormatter;

LocalDateTime now = LocalDateTime.now();

// 1. Define a formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// 2. Format: Convert LocalDateTime to String
String formattedDateTime = now.format(formatter);
System.out.println("Formatted: " + formattedDateTime);

// 3. Parse: Convert String back to LocalDateTime
String dateTimeStr = "2025-01-01 08:00:00";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeStr, formatter);
System.out.println("Parsed: " + parsedDateTime);

Java also provides some predefined formatters, such as DateTimeFormatter.ISO_LOCAL_DATE_TIME.

Calculating Time Differences

  • Period: Used to calculate the difference between two dates (LocalDate), in units of years, months, and days.
  • Duration: Used to calculate the difference between two time points (LocalTime, LocalDateTime, Instant), in units of days, hours, minutes, seconds, and nanoseconds.
java
// Period example
LocalDate startDate = LocalDate.of(2024, 1, 1);
LocalDate endDate = LocalDate.of(2025, 3, 15);
Period period = Period.between(startDate, endDate);
System.out.printf("Difference: %d years, %d months, %d days\n", period.getYears(), period.getMonths(), period.getDays());

// Duration example
LocalTime startTime = LocalTime.of(9, 0);
LocalTime endTime = LocalTime.of(10, 30, 15);
Duration duration = Duration.between(startTime, endTime);
System.out.println("Difference in seconds: " + duration.getSeconds());

Content is for learning and research only.