Blog Detail

  • Home
  • Java 8 new date and time API

Java 8 new date and time API

In this blog I have posted the sample code for new date time API. like get the current date, time, zoneId, and get next SATURDAY. and formatting date. The old java Date is not thread safe, the new date time API is thread safe.

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 =;
		System.out.println("Current date: "+localDate);
		LocalTime localTime =;
		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 =, 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);


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

Write a comment