Java 8 new date and time API

The new Date and Time API introduce in Java 8 because of the bad design and concurrency issue in the old Date API.

In this blog, I have posted the sample code for new date time API. Like getting the current date, time, zoneId, and get next SATURDAY. And formatting the date.

Date and Time Classes

  • LocalDate : can get the system date
  • LocalTime : can get the system time
  • LocalDateTime : Combination of LocalDate and LocalTime
  • ZonedDateTime : Can get the zone specific date and time
  • DateTimeFormatter : Replacement of SimpleDateFormat
  • TemporalAdjusters : utility class, provide some static method to find previous or next date of particular days.

Sample code for new Date and Time API

package com.samplecoder.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

public class DateTime {
	public static void main(String... arg) {
		LocalDate localDate = LocalDate.now();
		System.out.println("Current date: "+localDate);
		
		LocalTime localTime = LocalTime.now();
		System.out.println("Current Time: "+localTime);
		
		LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
		System.out.println("Current Date&Time: "+localDateTime);
		
		ZoneId zoneId = ZoneId.systemDefault();
		System.out.println("System default time zone: "+zoneId);
		
		ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
		System.out.println("Current Zoned Date&Time: "+zonedDateTime);
		System.out.println("Format Date: "+localDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")));

		localDate = localDate.plus(2, ChronoUnit.DAYS);
		System.out.println("Plus 2 Days from current date: "+localDate.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")));
		System.out.println("Day of week: "+localDateTime.getDayOfWeek());
		System.out.println("Day of month: "+localDateTime.getDayOfMonth());
		System.out.println("Day of year: "+localDateTime.getDayOfYear());
		System.out.println("Year: "+localDateTime.getYear());
		
		LocalDateTime nextSaturday = localDateTime.with( TemporalAdjusters.firstDayOfMonth()).with(TemporalAdjusters.previousOrSame(DayOfWeek.FRIDAY));
		System.out.println("Next Saturday: "+nextSaturday);
	}
}

Result

Current date: 2021-07-20
Current Time: 07:46:41.189
Current Date&Time: 2021-07-20T07:46:41.189
System default time zone: Asia/Calcutta
Current Zoned Date&Time: 2021-07-20T07:46:41.189+05:30[Asia/Calcutta]
Format Date: 07/20/2021
Plus 2 Days from current date: 07/22/2021
Day of week: TUESDAY
Day of month: 20
Day of year: 201
Year: 2021
Next Saturday: 2021-06-25T07:46:41.189

Conclusion

I believe you have some understanding about new Date Time API in Java 8. And you know the use of TemporalAdjusters and DateTimeFormatter.