Java - ofXXX() Methods

Introduction

Classes in the Date-Time API do not provide public constructors to create their objects.

They let you create objects through static factory methods named ofXXX().

The following snippet of code shows how to create objects of the LocalDate class:

Demo

import java.time.LocalDate;
import java.time.Month;

public class Main {
  public static void main(String[] args) {
    LocalDate ld1 = LocalDate.of(2012, 5, 2); // 2012-05-02
    LocalDate ld2 = LocalDate.of(2012, Month.JULY, 4); // 2012-07-04
    LocalDate ld3 = LocalDate.ofEpochDay(2002); // 1975-06-26
    LocalDate ld4 = LocalDate.ofYearDay(2014, 40); // 2014-02-09
    System.out.println(ld1);//  w  w  w. j  a v  a2 s  . co  m
    System.out.println(ld2);
    System.out.println(ld3);
    System.out.println(ld4);
  }
}

Result

Obtaining Current Date, Time, and Datetime, and Constructing a Date

Demo

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import static java.time.Month.JANUARY;

public class Main {
        public static void main(String[] args) {
                // Get current date, time, and datetime
                LocalDate dateOnly = LocalDate.now();
                LocalTime timeOnly = LocalTime.now();
                LocalDateTime dateTime = LocalDateTime.now();
                ZonedDateTime dateTimeWithZone = ZonedDateTime.now();

                System.out.println("Current Date: " + dateOnly);
                System.out.println("Current Time: " + timeOnly);
                System.out.println("Current Date and Time: " + dateTime);
                System.out.println("Current Date, Time, and Zone: " + dateTimeWithZone);
                // Construct a birth date and time from date-time components
                LocalDate myBirthDate = LocalDate.of(1968, JANUARY, 12);
                LocalTime myBirthTime = LocalTime.of(7, 30);
                System.out.println("My Birth Date: " + myBirthDate);
                System.out.println("My Birth Time: " + myBirthTime);
        }//  w  w  w .j  a v  a2  s . c  o m
}

Result