Search⌘ K

Creating Date/Time Objects and Enums

Explore how to create immutable LocalDate and LocalDateTime objects with Java 8's Date and Time API. Learn to utilize enums like Month and ChronoUnit for clearer, safer date calculations and understand methods to handle current and future dates effectively.

We'll cover the following...

Creating date and time objects

Creating new date and time objects is much easier and less error-prone in Java 8. Every type is immutable and has static factory methods. For example, creating a new LocalDate for March 15, 2014 is as simple as:

Java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class datetime {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2014, 3, 15);
System.out.println(date);
}
}

For more type safety, we can use the new Month enum:

Java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
public class datetime {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2014, Month.MARCH, 15);
System.out.println(date);
}
}

We can also easily create a LocalDateTime by combining an ...