Working with Date and Time Objects in the Java 8 Date/Time API
Java 8 has introduced a new Date and Time API that is more intuitive and less cumbersome than the standard java.util.Date
and java.util.Calendar
packages. The new date and time API is located in java.time
. You can create a local date/time object that contains both the date and the time (including milliseconds, a local time object containing only the time, and a local date object containing only the date. To obtain the current date and/or time, you will use the now
method. To create other times and/or dates, you will use the of
method. To learn how to work with date and time objects in Java 8, follow these four steps.
- Open your text editor and create the Java program that will demonstrate working with date and time objects. Type in the following Java statements:
import java.time.*; public class WorkingWithDateAndTime { public static void main (String args[]) { // Create a local date time object: LocalDateTime today=LocalDateTime.now(); System.out.format("Current date and time is %s\n", today); // Create a local time object: LocalTime timeNow=LocalTime.now(); System.out.format("Current time is %s\n", timeNow); // Create a local date object: LocalDate dateToday=LocalDate.now(); System.out.format("Current date is %s\n" , dateToday); // Create a date time object from a date object and a time object: LocalDateTime todayFromDateAndTime=LocalDateTime.of(dateToday, timeNow); System.out.format("Current date and time date from date and time objects is %s\n", todayFromDateAndTime); // Create a date time of July 4, 1988 4AM: LocalDateTime july4_1988_4AM=LocalDateTime.of(1988, Month.JULY, 4, 4, 0, 0); System.out.format("Fourth of July, 1988 at 4AM: %s\n", july4_1988_4AM); } }
The
LocalDateTime
class can be used to create a date time object. Thenow
method returns an object representing the current date and current time. TheLocalTime
andLocalDate
classes also support anow
method that returns the current time or current date, respectively. We also create a date/time object from the local date and time objects using theof
method. In addition, you can use theof
method to create a date/time object with a past or future value. In the program we create a date time object representing July 4, 1988. - Save your file as
WorkingWithDateAndTime.java
. - Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter.
- You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter. Notice the output shows the values of the various date and time objects that you created.