Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
New Date & Time API in Java 8

New Date & Time API in Java 8

Overview

Java 8 introduced a new Date and Time API under the package java.time. This new API is more comprehensive and provides a better alternative to the legacy java.util.Date and java.util.Calendar classes. The new API is immutable and thread-safe, designed to address the shortcomings of the old date and time classes.

Main Classes in the New Date & Time API

  • LocalDate: Represents a date (year, month, day) without time.
  • LocalTime: Represents a time (hour, minute, second, nanosecond) without date.
  • LocalDateTime: Combines date and time without timezone information.
  • ZonedDateTime: Combines date and time with timezone information.
  • Period: Represents a date-based amount of time (e.g., 3 years, 2 months, 1 day).
  • Duration: Represents a time-based amount of time (e.g., 5 hours, 30 minutes).
  • Instant: Represents a specific moment on the timeline in UTC.
  • ZoneId: Represents a timezone identifier.

Creating Date and Time Objects

You can create date and time objects using various factory methods such as now(), of(), and parse().

Example: Creating Date and Time Objects

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.Instant;

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

        // Specific date
        LocalDate specificDate = LocalDate.of(2020, 1, 1);
        System.out.println("Specific Date: " + specificDate);

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

        // Specific time
        LocalTime specificTime = LocalTime.of(12, 30, 45);
        System.out.println("Specific Time: " + specificTime);

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

        // Specific date and time
        LocalDateTime specificDateTime = LocalDateTime.of(2020, 1, 1, 12, 30, 45);
        System.out.println("Specific DateTime: " + specificDateTime);

        // Current date and time with timezone
        ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
        System.out.println("Current ZonedDateTime: " + currentZonedDateTime);

        // Specific date and time with timezone
        ZonedDateTime specificZonedDateTime = ZonedDateTime.of(2020, 1, 1, 12, 30, 45, 0, ZoneId.of("America/New_York"));
        System.out.println("Specific ZonedDateTime: " + specificZonedDateTime);

        // Current instant
        Instant currentInstant = Instant.now();
        System.out.println("Current Instant: " + currentInstant);
    }
}

Manipulating Date and Time Objects

You can manipulate date and time objects using methods such as plus(), minus(), and with().

Example: Manipulating Date and Time Objects

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class DateTimeManipulationExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2020, 1, 1);
        System.out.println("Original Date: " + date);

        // Adding days
        LocalDate newDate = date.plusDays(10);
        System.out.println("New Date: " + newDate);

        // Subtracting months
        LocalDate previousDate = date.minusMonths(1);
        System.out.println("Previous Date: " + previousDate);

        LocalTime time = LocalTime.of(12, 30, 45);
        System.out.println("Original Time: " + time);

        // Adding hours
        LocalTime newTime = time.plusHours(5);
        System.out.println("New Time: " + newTime);

        // Subtracting minutes
        LocalTime previousTime = time.minusMinutes(15);
        System.out.println("Previous Time: " + previousTime);

        LocalDateTime dateTime = LocalDateTime.of(2020, 1, 1, 12, 30, 45);
        System.out.println("Original DateTime: " + dateTime);

        // Adding weeks
        LocalDateTime newDateTime = dateTime.plusWeeks(2);
        System.out.println("New DateTime: " + newDateTime);

        // Subtracting seconds
        LocalDateTime previousDateTime = dateTime.minusSeconds(30);
        System.out.println("Previous DateTime: " + previousDateTime);

        // Using with method to set specific fields
        LocalDateTime updatedDateTime = dateTime.withHour(15).withMinute(0);
        System.out.println("Updated DateTime: " + updatedDateTime);
    }
}

Formatting and Parsing Date and Time

The DateTimeFormatter class is used to format and parse date and time objects.

Example: Formatting and Parsing Date and Time

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormattingExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        // Formatting date
        String formattedDate = date.format(formatter);
        System.out.println("Formatted Date: " + formattedDate);

        // Parsing date
        String dateString = "25/12/2020";
        LocalDate parsedDate = LocalDate.parse(dateString, formatter);
        System.out.println("Parsed Date: " + parsedDate);

        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

        // Formatting datetime
        String formattedDateTime = dateTime.format(dateTimeFormatter);
        System.out.println("Formatted DateTime: " + formattedDateTime);

        // Parsing datetime
        String dateTimeString = "25/12/2020 10:15:30";
        LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, dateTimeFormatter);
        System.out.println("Parsed DateTime: " + parsedDateTime);
    }
}