Pages

Wednesday, November 25, 2020

Java 8 LocalDateTime Class With Examples

1. Overview

In thus tutorial, You'll learn how to use and work with the LocalDateTime class in java 8.

LocalDateTime is a new class that added in java 8 Date Time api to simplify the date operations developer friendly such as converting date to string and string to data, adding days or months or years to date part, subtracting days, months or years to date.

And also you can add or remove hours, minutes or seconds. And also many more operations.

But, Java 8 LocalDate class does work and operated on only date format in such way for year, months and days.

And also another class Java 8 LocalTime class does and operates only date time part such as on hours, minutes and seconds or nano seconds.

Let us see the LocalDateTime class methods with example programs.

Java 8 LocalDateTime Class With Examples



2. Java 8 LocalDateTime Methods

LocalDateTime class is also an immutable date-time object like LocalDate and LocalTime and that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

String format(DateTimeFormatter formatter): It is used to format this date-time using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this date-time as an int.

LocalDateTime minusDays(long days): It is used to return a copy of this LocalDateTime with the specified number of days subtracted.

static LocalDateTime now(): It is used to obtain the current date-time from the system clock in the default time-zone.

static LocalDateTime of(LocalDate date, LocalTime time): It is used to obtain an instance of LocalDateTime from a date and time.

LocalDateTime plusDays(long days): It is used to return a copy of this LocalDateTime with the specified number of days added.

boolean equals(Object obj): It is used to check if this date-time is equal to another date-time.

public LocalDate toLocalDate(): It is used to convert from LocalDateTime to LocalDate

public LocalTime toLocalTime(): It is used to convert from LocalDateTime to LocalTime

public int getYear(): It is used to get the year value from datetime.

public int getHour(): It is used to get the hour value from range 0 to 23

public int getMinute(): It is used to get the minute value from range 0 to 59

public int getSecond(): It is used to get the second value from range 0 to 59

public int getNano(): It is used to get the nano value from range 0 to 999,999,999

public int getMonthValue(): It is used to get the month of the year value from range 1 to 12

public LocalDateTime plus(long amountToAdd, TemporalUnit unit): It is used to add the specified amount in the given time units. 

public LocalDateTime minus(long amountToSubtract, TemporalUnit unit): It is used to subtract the specified amount in the given time units. 


3. LocalDateTime Method Examples

Let explore the different date operations using LocalDateTime methods.

3.1 LocalDateTime Object Creation

Use now() or of() method to create the LocalDateTime object. now() method is to get the current date and time and of() method creates the LocalDateTime object though the date custom parameters passed to of() method.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;

public class LocalDateTimeCreationExample {

	public static void main(String[] args) {
		// Creating the current date and time using LocalDateTime.now() method
		LocalDateTime currentDatetime = LocalDateTime.now();
		System.out.println("Current date time : "+currentDatetime);

		// Creating the future date and time using LocalDateTime.of() method
		LocalDateTime futureDateTime = LocalDateTime.of(2025, 01, 01, 00, 45);
		System.out.println("Future date time : "+futureDateTime);
	}
}
 

Output:

Current date time : 2020-11-25T20:12:01.733193
Future date time : 2025-01-01T00:45
 

From the output, you can see that now() method produces the output with the nano seconds where as of() method created the date using given time parameters without adding the nano seconds.

3.2 LocalDateTime To String Conversion

Converting LocalDateTime object to String is done using format() method. 

First, Create the LocalDateTime object using now() method.

Next, call format() method with the date format that is needed in string format.

Finally, stored the returned value into a String variable.

package com.javaprogramto.java8.dates.localdatetime;

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

public class LocalDateTimeToStringExample {

	public static void main(String[] args) {
		// Getting current date and time using now() method
		LocalDateTime currentDatetime = LocalDateTime.now();
		System.out.println("Current date time : " + currentDatetime);

		// Date format in yyyy-MMM-dd hh:mm
		DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm");

		// converting LocalDateTime to String type
		String dateInStr = currentDatetime.format(dateFormat);
		System.out.println("Date time in string : " + dateInStr);
	}
}
 

Output:

Current date time : 2020-11-25T20:20:01.410561
Date time in string : 2020-Nov-25 08:20
 

In the above example, converted current date time into string format of "yyyy-MMM-dd hh:mm".

3.3 LocalDateTime.get() - Getting the specified date time part

Use get() method to get the specific time field from date time object as int value.

Enum ChronoField has several predefined constants and those can be passed to the get() method as shown in the below example to get year, month, day, hour, minute, second.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class LocalDateTimeToStringExample {

	public static void main(String[] args) {
		// Creating the date time object using of() method
		LocalDateTime datetime = LocalDateTime.of(2020, 10, 30, 23, 50, 59);
		System.out.println("Date time : " + datetime);

		//
		int year = datetime.get(ChronoField.YEAR);
		int month = datetime.get(ChronoField.MONTH_OF_YEAR);
		int day = datetime.get(ChronoField.DAY_OF_MONTH);
		int hour = datetime.get(ChronoField.HOUR_OF_DAY);
		int minute = datetime.get(ChronoField.MINUTE_OF_HOUR);
		int second = datetime.get(ChronoField.SECOND_OF_MINUTE);
		
		
		System.out.println("year : "+year);
		System.out.println("month : "+month);
		System.out.println("day : "+day);
		System.out.println("hour : "+hour);
		System.out.println("minute : "+minute);
		System.out.println("second : "+second);
	}
}
 

Output:

Date time : 2020-10-30T23:50:59
year : 2020
month : 10
day : 30
hour : 23
minute : 50
second : 59
 

3.4 LocalDateTime.plus() - Adding days or months or years or any date time part

This class has several methods to add date fields to the existing date and returns a new copy with the modified fields.

public LocalDateTime plus(long amountToAdd, TemporalUnit unit)

public LocalDateTime plusYears(long years)

public LocalDateTime plusMonths(long months)

public LocalDateTime plusWeeks(long weeks)

public LocalDateTime plusDays(long days)

public LocalDateTime plusHours(long hours)

public LocalDateTime plusMinutes(long minutes)

public LocalDateTime plusSeconds(long seconds)

public LocalDateTime plusNanos(long nanos)

Use the above methods as needed to modify the date time fields and the resulted new object gets the new changes.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimePlusExample {

	public static void main(String[] args) {
		// Creating the date time object using of() method
		LocalDateTime datetime = LocalDateTime.of(2020, 10, 30, 23, 50, 55);
		System.out.println("Date time : " + datetime);

		// using plus(long, TemporalUnit)
		LocalDateTime yearModifed = datetime.plus(2, ChronoUnit.YEARS);
		LocalDateTime monthsModifed = datetime.plus(2, ChronoUnit.MONTHS);

		// using plusXXX() methods
		LocalDateTime daysModifed = datetime.plusDays(2);
		LocalDateTime hoursModifed = datetime.plusHours(2);
		LocalDateTime minssModifed = datetime.plusMinutes(2);
		LocalDateTime secsModifed = datetime.plusSeconds(2);
		LocalDateTime nanosModifed = datetime.plusNanos(2);

		System.out.println("years added : " + yearModifed);
		System.out.println("months added: " + monthsModifed);
		System.out.println("days added : " + daysModifed);
		System.out.println("hours added : " + hoursModifed);
		System.out.println("minutes added : " + minssModifed);
		System.out.println("seconds added : " + secsModifed);
		System.out.println("nonos added : " + nanosModifed);
	}
}
 

Output:

Date time : 2020-10-30T23:50:55
years added : 2022-10-30T23:50:55
months added: 2020-12-30T23:50:55
days added : 2020-11-01T23:50:55
hours added : 2020-10-31T01:50:55
minutes added : 2020-10-30T23:52:55
seconds added : 2020-10-30T23:50:57
nonos added : 2020-10-30T23:50:55.000000002
 

3.5 LocalDateTime.minus() - Subtracting days or months or years or any date time part

This class has several methods to go back to the previous date fields to the existing date and returns a new copy with the modified fields.

public LocalDateTime minus(long amountToAdd, TemporalUnit unit)

public LocalDateTime minusYears(long years)

public LocalDateTime minusMonths(long months)

public LocalDateTime minusWeeks(long weeks)

public LocalDateTime minusDays(long days)

public LocalDateTime minusHours(long hours)

public LocalDateTime minusMinutes(long minutes)

public LocalDateTime minusSeconds(long seconds)

public LocalDateTime minusNanos(long nanos)

Use the above methods as needed to modify the date time fields and the resulted new object gets the new changes as plus() methods.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeMinusExample {

	public static void main(String[] args) {
		// Creating the date time object using of() method
		LocalDateTime datetime = LocalDateTime.of(2020, 10, 30, 23, 50, 55);
		System.out.println("Date time : " + datetime);

		// using minus(long, TemporalUnit)
		LocalDateTime yearModifed = datetime.minus(2, ChronoUnit.YEARS);
		LocalDateTime monthsModifed = datetime.minus(2, ChronoUnit.MONTHS);

		// using minusXXX() methods
		LocalDateTime daysModifed = datetime.minusDays(2);
		LocalDateTime hoursModifed = datetime.minusHours(2);
		LocalDateTime minssModifed = datetime.minusMinutes(2);
		LocalDateTime secsModifed = datetime.minusSeconds(2);
		LocalDateTime nanosModifed = datetime.minusNanos(2);

		System.out.println("years substracted : " + yearModifed);
		System.out.println("months substracted: " + monthsModifed);
		System.out.println("days substracted : " + daysModifed);
		System.out.println("hours substracted : " + hoursModifed);
		System.out.println("minutes substracted : " + minssModifed);
		System.out.println("seconds substracted : " + secsModifed);
		System.out.println("nonos substracted : " + nanosModifed);
	}
}
 

Output:

Date time : 2020-10-30T23:50:55
years substracted : 2018-10-30T23:50:55
months substracted: 2020-08-30T23:50:55
days substracted : 2020-10-28T23:50:55
hours substracted : 2020-10-30T21:50:55
minutes substracted : 2020-10-30T23:48:55
seconds substracted : 2020-10-30T23:50:53
nonos substracted : 2020-10-30T23:50:54.999999998
 

4. Conclusion

In this article, you've seen most useful methods of LocalDateTime class in java 8 with examples.

All the methods of this class results in a new copy of date time object with the new changes applied to it and need to store it back to the new LocalDateTime reference.

GitHub

Read Next

Java 8 LocalDate Examples

Java 8 LocalTime Examples

Java 8 Date Time API Examples

LocalDateTime API

No comments:

Post a Comment

Please do not add any spam links in the comments section.