Java - atXXX( ) Methods

Introduction

atXXX() method builds a new datetime object from an existing datetime object by adding additional information.

withXXX() methods lets you create a copy of an object by changing its fields.

Suppose you have the date 2012-05-02.

To create a new date of 2012-07-02 (with month changed to 7), use a withXXX() method.

To create a datetime of 2012-05-02T15:30 (by adding time 15:30), use an atXXX() method.

Some examples of using atXXX() methods are shown below.

LocalDate ld = LocalDate.of(2012, 5, 2);  // 2012-05-02
LocalDateTime ldt1 = ld.atStartOfDay();   // 2012-05-02T00:00
LocalDateTime ldt2 = ld.atTime(15, 30);   // 2012-05-02T15:30

The following snippet of code shows how to use a builder pattern to build a local date:

// Use a builder pattern to build a date 2012-05-22
LocalDate d1 = Year.of(2012).atMonth(5).atDay(22);

// Use an of() factory method to build a date 2012-05-22
LocalDate d2 = LocalDate.of(2012, 5, 22);

Demo

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;

public class Main {
  public static void main(String[] args) {
    LocalDate ld = LocalDate.of(2012, 5, 2);  // 2012-05-02
    System.out.println(ld);//from w  w w. ja v  a 2s .  c om
    LocalDateTime ldt1 = ld.atStartOfDay();   // 2012-05-02T00:00
    System.out.println(ldt1);
    LocalDateTime ldt2 = ld.atTime(15, 30);   // 2012-05-02T15:30
    System.out.println(ldt2);
 // Use a builder pattern to build a date 2012-05-22
    LocalDate d1 = Year.of(2012).atMonth(5).atDay(22);
    System.out.println(d1);
    // Use an of() factory method to build a date 2012-05-22
    LocalDate d2 = LocalDate.of(2012, 5, 22);
    System.out.println(d2);
  }
}

Result