Java 8 - LocalDateTime example

Posted on May 30, 2017


The java.time.LocalDateTime class is an immutable class which represents a date-time without time-zone information such as ‘2017-07-12T10:35:55’.

This class does not store and represent time-zone. Instead, it is a description of the date-time which can be viewed as year-month-day-hour-minute-second.

The following examples are provided to demonstrate the usage of the LocalDateTime in java program.

How to create a LocalDateTime in Java

You can use the LocalDateTime.now() and LocalDateTime.of() methods to create the current date-time and specific date-time object respectively.

package com.boraji.tutorial.datetime;

import java.time.Clock;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;

public class LocalDateTimeExample {
   public static void main(String[] args) {
      // Current date time
      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println(dateTime);

      // Current date time from specified time-zone
      LocalDateTime dateTime2 = LocalDateTime.now(ZoneId.of("UTC"));
      System.out.println(dateTime2);

      // Current date time from specified clock
      LocalDateTime dateTime3 = LocalDateTime.now(Clock.systemUTC());
      System.out.println(dateTime3);

      // Specific date time
      LocalDateTime dateTime4 = LocalDateTime.of(2017, Month.JULY, 12, 10, 35, 55);
      System.out.println(dateTime4);

   }
}

Output 

2017-05-30T21:51:46.004
2017-07-12T10:35:55
2017-05-30T16:21:46.004
2017-05-30T16:21:46.004

How to get year, month, day from LocalDateTime

You can use the getYear()getMonth() and getDayOfMonth() methods of the LocalDateTime class to get year, month and day respectively.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println("Year : " + dateTime.getYear());
      System.out.println("Month : " + dateTime.getMonth().getValue());
      System.out.println("Day of Month : " + dateTime.getDayOfMonth());
      System.out.println("Day of Week : " + dateTime.getDayOfWeek());
      System.out.println("Day of Year : " + dateTime.getDayOfYear());
   }
}

Output

Year : 2017
Month : 5
Day of Month : 30
Day of Week : TUESDAY
Day of Year : 150

How to get Hour, Minute, Second from LocalDateTime

You can use the getHour()getMinute() and getSecond() methods of the LocalDateTime class to get hour, minute and second respectively.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println("Hour : " + dateTime.getHour());
      System.out.println("Minute : " + dateTime.getMinute());
      System.out.println("Second : " + dateTime.getSecond());
      System.out.println("Nano : "+dateTime.getNano());
   }
}

Output

Hour : 22
Minute : 16
Second : 41
Nano : 90000000

How to add or subtract years, months, days, hours, minutes and seconds to LocalDateTime

You can use the plus and minus methods of the LocalDateTime class to add or subtract days, months, hours, minutes etc.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      // LocalDateTime's plus methods 
      System.out.println("Addition of days : " + dateTime.plusDays(5));
      System.out.println("Addition of months : " + dateTime.plusMonths(15));
      System.out.println("Addition of years : " + dateTime.plusYears(5));
      System.out.println("Addition of Hours : " + dateTime.plusHours(2));
      System.out.println("Addition of Minutes : " + dateTime.plusMinutes(30));
      System.out.println("Addition of Seconds : " + dateTime.plusSeconds(20));

      // LocalDateTime's minus methods 
      System.out.println("Subtraction of days : " + dateTime.minusDays(5));
      System.out.println("Subtraction of months : " + dateTime.minusMonths(15));
      System.out.println("Subtraction of years : " + dateTime.minusYears(5));
      System.out.println("Subtraction of Hours : " + dateTime.minusHours(2));
      System.out.println("Subtraction of Minutes : " + dateTime.minusMinutes(30));
      System.out.println("Subtraction of Seconds : " + dateTime.minusSeconds(20));
   }
}

Output

Addition of days : 2017-06-04T22:23:02.513
Addition of months : 2018-08-30T22:23:02.513
Addition of years : 2022-05-30T22:23:02.513
Addition of Hours : 2017-05-31T00:23:02.513
Addition of Minutes : 2017-05-30T22:53:02.513
Addition of Seconds : 2017-05-30T22:23:22.513
Subtraction of days : 2017-05-25T22:23:02.513
Subtraction of months : 2016-02-29T22:23:02.513
Subtraction of years : 2012-05-30T22:23:02.513
Subtraction of Hours : 2017-05-30T20:23:02.513
Subtraction of Minutes : 2017-05-30T21:53:02.513
Subtraction of Seconds : 2017-05-30T22:22:42.513

How to compare LocalDateTime objects in Java

You can use the isEqual(), compareTo()isAfter() and isBefore() methods of the LocalDateTime class to compare the LocalDateTime objects.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime1 = LocalDateTime.of(2017, 05, 22, 10, 55, 25);
      LocalDateTime dateTime2 = LocalDateTime.of(2017, 06, 11, 05, 35, 26);
      LocalDateTime dateTime3 = LocalDateTime.of(2017, 05, 22, 10, 55, 25);

      // Using isBefore() method
      if (dateTime1.isBefore(dateTime2)) {
         System.out.println("dateTime1 is before dateTime2");
      }

      // Using isAfter() method
      if (dateTime2.isAfter(dateTime3)) {
         System.out.println("dateTime2 is after dateTime3");
      }

      // Using isEqual() method
      if (dateTime1.isEqual(dateTime3)) {
         System.out.println("dateTime1 is equal to dateTime3");
      }

      // Using compareTo() method
      if (dateTime1.compareTo(dateTime3) == 0) {
         System.out.println("dateTime1 is equal to dateTime3");
      }

   }
}

Output

dateTime1 is before dateTime2
dateTime2 is after dateTime3
dateTime1 is equal to dateTime3
dateTime1 is equal to dateTime3

 

How to convert LocalDateTime to LocalDate in Java

You can use the toLocalDate() method of the LocalDateTime class to get LocalDate from LocalDateTime.

package com.boraji.tutorial.datetime;

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

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println(dateTime);
      
      LocalDate localDate = dateTime.toLocalDate();
      System.out.println(localDate);
   }
}

Output

2017-05-31T21:30:14.841
2017-05-31

How to convert LocalDateTime to LocalTime in Java

You can use the toLocalTime() method of the LocalDateTime class to get LocalTime from LocalDateTime.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;
import java.time.LocalTime;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println(dateTime);
      
      LocalTime localDate = dateTime.toLocalTime();
      System.out.println(localDate);
   }
}

Output

2017-05-31T21:35:10.438
21:35:10.438

How to get number of days in a month or year using LocalDateTime

First, convert the LocalDateTime to LocalDate then use lengthOfMonth() and lengthOfYear() methods of the LocalDate class to count the number of days in a month and year respectively.

package com.boraji.tutorial.datetime;

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

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println(dateTime);

      // Convert LocalDateTime to LocalDate
      LocalDate localDate = dateTime.toLocalDate();
      
      // Number of days in a month
      System.out.println("Number of days in " + localDate.getMonth() + " : "
            + localDate.lengthOfMonth());
      System.out.println("Number of days in " + localDate.getMonth() + " : "
            + localDate.lengthOfMonth());

      // Number of days in a year
      System.out.println("Number of days in " + localDate.getYear() + " : "
            + localDate.lengthOfYear());
      System.out.println("Number of days in " + localDate.getYear() + " : "
            + localDate.lengthOfYear());
   }
}

Output

2017-05-31T21:42:54.732
Number of days in MAY : 31
Number of days in MAY : 31
Number of days in 2017 : 365
Number of days in 2017 : 365

How to check if a given year is leap year or not using LocalDateTime

First, convert the LocalDateTime to LocalDate then use isLeapYear() method of the LocalDate class to check whether a given year is leap year or not.

package com.boraji.tutorial.datetime;

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

public class LocalDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println(dateTime);

      // Convert LocalDateTime to LocalDate
      LocalDate localDate = dateTime.toLocalDate();
      if (localDate.isLeapYear()) {
         System.out.println(localDate.getYear() + " is a leap year");
      } else {
         System.out.println(localDate.getYear() + " is not a leap year");
      }
   }
}

Output

2017-05-31T21:48:07.627
2017 is not a leap year

How to convert or parse String to LocalDateTime in java

You can use the parse() method of the LocalDateTime class to convert the String to LocalDateTime.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      // ISO date time
      LocalDateTime dateTime1 = LocalDateTime.parse("2017-05-30T10:30:45",
            DateTimeFormatter.ISO_LOCAL_DATE_TIME);
      System.out.println(dateTime1);

      // 'yyyy-MMM-dd HH:mm:ss' pattern
      LocalDateTime dateTime2 = LocalDateTime.parse("2017-May-02 23:35:05",
            DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss"));
      System.out.println(dateTime2);

      // 'yyyy-MM-dd KK:mm:ss a' pattern
      LocalDateTime dateTime3 = LocalDateTime.parse("2017-05-30 10:20:30 AM",
            DateTimeFormatter.ofPattern("yyyy-MM-dd KK:mm:ss a"));
      System.out.println(dateTime3);

      // 'cccc, MMMM dd, yyyy KK:mm a' pattern
      LocalDateTime dateTime4 = LocalDateTime.parse("Wednesday, May 31, 2017 10:21 PM",
            DateTimeFormatter.ofPattern("cccc, MMMM dd, yyyy KK:mm a"));
      System.out.println(dateTime4);

   }
}

Output

2017-05-30T10:30:45
2017-05-02T23:35:05
2017-05-30T10:20:30
2017-05-31T22:21

 

How to convert or format LocalDateTime to String in java

You can use the format() method of the LocalDateTime class to convert the LocalDateTime to String.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample {
   public static void main(String[] args) {

      // ISO date time
      LocalDateTime dateTime = LocalDateTime.now();
      System.out.println(dateTime.format(
            DateTimeFormatter.ISO_LOCAL_DATE_TIME));

      // 'yyyy-MMM-dd HH:mm:ss' pattern
      System.out.println(dateTime.format(
            DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss")));

      // 'yyyy-MM-dd KK:mm:ss a' pattern
      System.out.println(dateTime.format(
            DateTimeFormatter.ofPattern("yyyy-MM-dd KK:mm:ss a")));

      // 'cccc, MMMM dd, yyyy KK:mm a' pattern
      System.out.println(dateTime.format(
            DateTimeFormatter.ofPattern("cccc, MMMM dd, yyyy KK:mm a")));
   }
}

Output

2017-05-31T22:26:58.161
2017-May-31 22:26:58
2017-05-31 10:26:58 PM
Wednesday, May 31, 2017 10:26 PM