Java LocalDateTime of()

In this guide, you will learn about the LocalDateTime of() method in Java programming and how to use it with an example.

1. LocalDateTime of() Method Overview

Definition:

The LocalDateTime.of() method allows users to obtain an instance of LocalDateTime from individual date and time parts.

Syntax:

There are multiple overloaded versions of the `of()` method. Some of them are:

1. static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute)
2. static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second)
3. static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
4. static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)

Parameters:

- year: The year to represent, from MIN_YEAR to MAX_YEAR

- month: The month-of-year to represent, not null

- dayOfMonth: The day-of-month to represent, from 1 to 31

- hour: The hour-of-day to represent, from 0 to 23

- minute: The minute-of-hour to represent, from 0 to 59

- second: The second-of-minute to represent, from 0 to 59

- nanoOfSecond: The nano-of-second to represent, from 0 to 999,999,999

Key Points:

- The LocalDateTime.of() method creates a LocalDateTime instance with the specified date and time values.

- It's a static factory method, so it can be invoked on the class itself.

- If any provided parameters are outside of their valid range, a DateTimeException will be thrown.

- LocalDateTime is part of the java.time package introduced in Java 8 and is immutable.

2. LocalDateTime of() Method Example

import java.time.LocalDateTime;
import java.time.Month;

public class LocalDateTimeOfExample {
    public static void main(String[] args) {
        // Create a LocalDateTime instance using the of() method
        LocalDateTime dateTime1 = LocalDateTime.of(2023, Month.SEPTEMBER, 20, 16, 30);
        LocalDateTime dateTime2 = LocalDateTime.of(2023, 9, 20, 16, 30, 45);
        LocalDateTime dateTime3 = LocalDateTime.of(2023, 9, 20, 16, 30, 45, 500);

        System.out.println("DateTime 1: " + dateTime1);
        System.out.println("DateTime 2: " + dateTime2);
        System.out.println("DateTime 3: " + dateTime3);
    }
}

Output:

DateTime 1: 2023-09-20T16:30
DateTime 2: 2023-09-20T16:30:45
DateTime 3: 2023-09-20T16:30:45.000000500

Explanation:

In the provided example, three different versions of the LocalDateTime.of() method are used.

- dateTime1 uses the version that accepts year, month, day, hour, and minute.

- dateTime2 includes the second.

- dateTime3 includes the second and nanosecond. 

The outputs correspond to the different precisions based on the provided arguments.

Comments