top of page

Java Date and Time API Tutorial

Welcome to Code with Pankaj! In this tutorial, we'll explore the Java Date and Time API, introduced in Java 8. This API provides a comprehensive set of classes for handling dates, times, and time zones, addressing many of the shortcomings of the older java.util.Date and java.util.Calendar classes.


Table of Contents


  1. Introduction to the Java Date and Time API

  2. Key Classes in the Java Date and Time API

  3. Creating Date and Time Objects]

  4. Manipulating Dates and Times

  5. Formatting and Parsing

  6. Working with Time Zones

  7. Period and Duration

  8. Practical Examples


Introduction to the Java Date and Time API


The Java Date and Time API is part of the java.time package. It was introduced to address several issues with the older date and time classes:


- Thread safety

- Better separation of dates and times

- More intuitive API

- Better support for different calendaring systems


To use the new API, you need to import the necessary classes:


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

 

Key Classes in the Java Date and Time API


  • LocalDate : Represents a date without time or time zone (e.g., 2023-08-31)

  • LocalTime : Represents a time without a date or time zone (e.g., 14:30:00)

  • LocalDateTime : Combines date and time, but still without a time zone

  • ZonedDateTime : A complete date-time with time zone information

  • Instant : Represents a point in time on the timeline (useful for timestamps)

  • Duration : Represents a time-based amount of time

  • Period : Represents a date-based amount of time


Creating Date and Time Objects


Let's look at how to create objects using these classes:


Current date


LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today);

Current time


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

Current date and time


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

Creating a specific date


LocalDate specificDate = LocalDate.of(2023, 8, 31);
System.out.println("Specific date: " + specificDate);

Creating a specific time


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

Manipulating Dates and Times


The API provides methods to easily manipulate dates and times:


LocalDate today = LocalDate.now();

Adding days


LocalDate nextWeek = today.plusDays(7);
System.out.println("Date after one week: " + nextWeek);

Subtracting months


LocalDate previousMonth = today.minusMonths(1);
System.out.println("Date from previous month: " + previousMonth);

Modifying specific fields


LocalDate firstDayOfMonth = today.withDayOfMonth(1);

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



Formatting and Parsing


The `DateTimeFormatter` class is used for formatting and parsing date-time objects:


 

LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedDate = date.format(dateFormatter);
String formattedTime = time.format(timeFormatter);
System.out.println("Formatted date: " + formattedDate);
System.out.println("Formatted time: " + formattedTime);
// Parsing
LocalDate parsedDate = LocalDate.parse("31/08/2023", dateFormatter);
System.out.println("Parsed date: " + parsedDate);

 

Working with Time Zones


The API provides robust support for working with time zones:


 


// Current date-time in system default time zone

ZonedDateTime nowInDefaultTZ = ZonedDateTime.now();

System.out.println("Current date-time in default time zone: " + nowInDefaultTZ);

// Current date-time in a specific time zone

ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");

ZonedDateTime tokyoTime = ZonedDateTime.now(tokyoZone);

System.out.println("Current date-time in Tokyo: " + tokyoTime);

// Converting between time zones

ZoneId newYorkZone = ZoneId.of("America/New_York");

ZonedDateTime newYorkTime = tokyoTime.withZoneSameInstant(newYorkZone);

System.out.println("Tokyo time in New York: " + newYorkTime);

 

Period and Duration


`Period` and `Duration` are used to represent amounts of time:


 

LocalDate start = LocalDate.of(2023, 1, 1);

LocalDate end = LocalDate.of(2023, 12, 31);

Period period = Period.between(start, end);

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

LocalTime startTime = LocalTime.of(9, 0);

LocalTime endTime = LocalTime.of(17, 30);

Duration duration = Duration.between(startTime, endTime);

System.out.println("Duration: " + duration.toHours() + " hours, " + duration.toMinutesPart() + " minutes");


Practical Examples


Let's look at some practical examples to solidify our understanding:


Example 1: Age Calculator


public static int calculateAge(LocalDate birthDate) {

    LocalDate currentDate = LocalDate.now();

    if (birthDate != null) {

        return Period.between(birthDate, currentDate).getYears();

    } else {

        return 0;

    }

}

// Usage

LocalDate birthDate = LocalDate.of(1990, 5, 15);

int age = calculateAge(birthDate);

System.out.println("Age: " + age + " years");

Example 2: Next Friday Finder




public static LocalDate findNextFriday(LocalDate startDate) {

    return startDate.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));

}

// Usage

LocalDate today = LocalDate.now();

LocalDate nextFriday = findNextFriday(today);

System.out.println("Next Friday: " + nextFriday);

Example 3: Time Zone Converter


public static void printTimeInDifferentZones(LocalDateTime dateTime) {

    ZoneId londonZone = ZoneId.of("Europe/London");

    ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");

    ZoneId newYorkZone = ZoneId.of("America/New_York");

    ZonedDateTime londonTime = dateTime.atZone(londonZone);

    ZonedDateTime tokyoTime = londonTime.withZoneSameInstant(tokyoZone);

    ZonedDateTime newYorkTime = londonTime.withZoneSameInstant(newYorkZone);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

    System.out.println("London time: " + londonTime.format(formatter));

    System.out.println("Tokyo time: " + tokyoTime.format(formatter));

    System.out.println("New York time: " + newYorkTime.format(formatter));

}

// Usage

LocalDateTime dateTime = LocalDateTime.of(2023, 8, 31, 12, 0);

printTimeInDifferentZones(dateTime);

This concludes our tutorial on the Java Date and Time API. With these tools and examples, you should be well-equipped to handle various date and time operations in your Java applications. Remember to practice and explore the API further to become proficient in using it.


Happy coding with Pankaj !

Related Posts

See All

Comments


bottom of page