Java LocalDateTime

Filed Under: Java

Java LocalDateTime class is part of Java 8 Date API.

Java LocalDateTime

  1. Java LocalDateTime is an immutable class, so it’s thread safe and suitable to use in multithreaded environment.
  2. LocalDateTime provides date and time output in the format of YYYY-MM-DD-hh-mm-ss.zzz, extendable to nanosecond precision. So we can store “2017-11-10 21:30:45.123456789” in LocalDateTime object.
    Java LocalDateTime
  3. Just like the LocalDate class, LocalDateTime has no time zone data. We can use LocalDateTime instance for general purpose date and time information.
  4. LocalDateTime class implements Comparable, ChronoLocalDateTime, Temporal, TemporalAdjuster, TermporalAccessor and Serializable interfaces.
  5. LocalDateTime is a final class, so we can’t extend it.
  6. LocalDateTime is a value based class, so we should use equals() method to check if two instances of LocalDateTime are equal or not.
  7. LocalDateTime class is a synergistic ‘combination’ of LocalDate and LocalTime with the contatenated format as shown in the figure above.

Importing Java LocalDateTime Class

Java LocalDateTime class is part of java.time package. So we can import it like following:


import java.time.LocalDateTime;

Creating LocalDateTime instance

There are following ways to create LocalDateTime object.

  1. Invoking the static now() method that returns the current date-time from the system clock in the default time-zone.
    
    LocalDateTime ldt = LocalDateTime.now();
    
  2. By passing year, month, day, hour, minute, second and nanosecond values to of() method. This method is overloaded and one of them takes argument at LocalDate and LocalTime.
    
    LocalDateTime ldt = LocalDateTime.of(2017,11,6,6,30,40,50000);
    		
    ldt = LocalDateTime.of(LocalDate.now(), LocalTime.now());
    
  3. Using parse() method and passing date time string representation.
    
    LocalDateTime ldt = LocalDateTime.parse("2017-11-10T22:11:03.460446");
    
  4. Using ofInstant() by passing Instant and ZoneId information.
    
    LocalDateTime ldt = LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
    

Retrieving Date Time Information from LocalDateTime instance

Let’s look into some of the LocalDateTime methods to retrieve date time information.

  1. getHour(): returns the int hour contained within the LocalDateTime object, from 0 to 23.
  2. getMinute(): returns the int minute information, from 0 to 59.
  3. getSecond(): returns the int second contained within the LocalDateTime object, from 0 to 59.
  4. getNano(): returns the int nanosecond from the LocalDateTime object, ranging from 0 to 999,999,999.

Apart from above, LocaDate class stock methods such as getYear(), getMonth(), getDayOfMonth(), getDayOfWeek(), getDayOfYear() are also applicable to LocalDateTime class. Let’s look at these methods through an example.

Java LocalDateTime Example


package com.journaldev.java;

import java.time.LocalDateTime;

public class JavaLocalDateTimeExample {

	public static void main(String[] args) {

		LocalDateTime ldt = LocalDateTime.of(2017, 11, 6, 6, 30, 40, 50000);

		System.out.println("Hour = " + ldt.getHour());
		System.out.println("Minute = " + ldt.getMinute());
		System.out.println("Second = " + ldt.getSecond());
		System.out.println("Nano = " + ldt.getNano());

		System.out.println("Year = " + ldt.getYear());
		System.out.println("Month = " + ldt.getMonth());
		System.out.println("Date = " + ldt.getDayOfMonth());

	}

}

Java LocalDateTime Example, Java 8 LocalDateTime

Java LocalDateTime methods – plus and minus

LocalDateTime class has many methods to plus and minus date time components. Note that it returns a copy of the LocalDateTime object with the change, no change happens in the specified object. Some of these methods are:

  1. plusHours(), plusMinutes(), plusSeconds() and plusNanos() for adding time component in LocalDateTime object.
  2. minusHours(), minusMinutes(), minusSeconds() and minusNanos() for subtracting time component in LocalDateTime object.
  3. plusYears(), plusMonths(), plusWeeks() and plusDays() for adding date component in LocalDateTime object.
  4. minusYears(), minusMonths(), minusWeeks() and minusDays() for subtracting date component in LocalDateTime object.

All the above method take long argument, their names clearly suggests what they are used for.

Here is an example for LocalDateTime plus and minus methods.


package com.journaldev.java;

import java.time.LocalDateTime;

public class JavaLocalDateTimeExample {

	public static void main(String[] args) {

		LocalDateTime ldt = LocalDateTime.of(2017, 11, 10, 6, 0);
		System.out.println(ldt);
		
		//adding 1 year, 1 month, 1 week and 1 day
		LocalDateTime ldt1 = ldt.plusYears(1).plusMonths(1).plusWeeks(1).plusDays(1);
		System.out.println(ldt1);
		
		// subtracting 1 year, 1 month, 1 week and 1 day
		LocalDateTime ldt2 = ldt1.minusYears(1).minusMonths(1).minusWeeks(1).minusDays(1);
		System.out.println(ldt2);
		
		//adding 1 hour, 1 minute, 1 second and 100 nanos
		LocalDateTime ldt3 = ldt2.plusHours(1).plusMinutes(1).plusSeconds(1).plusNanos(100);
		System.out.println(ldt3);
				
		// subtracting 1 hour, 1 minute, 1 second and 100 nanos
		LocalDateTime ldt4 = ldt3.minusHours(1).minusMinutes(1).minusSeconds(1).minusNanos(100);
		System.out.println(ldt4);
				
	}
}

Output of above program is:


2017-11-10T06:00
2018-12-18T06:00
2017-11-10T06:00
2017-11-10T07:01:01.000000100
2017-11-10T06:00

As you can see that if the second and nano values are 0, then it’s not getting returned when we call LocalDateTime toString() method.

Java LocalDateTime to Date

We should avoid using legacy java.util.Date class, but if required then we can convert LocalDateTime to Date using below code.


LocalDateTime ldt = LocalDateTime.of(2017, 11, 10, 6, 0);
Date date = Date.from(ldt.toInstant(ZoneOffset.UTC));
System.out.println(date); // prints "Fri Nov 10 11:30:00 IST 2017"

Note that above output is because the LocalDateTime doesn’t have timezone information, so we need to provide timezone to offset and convert to local timezone.

That’s all for java LocalDateTime class.

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages