$show=/label

Java 8 LocalDateTime Class With Examples

SHARE:

A quick guide to LocalDateTime in java 8 with example programs. LocalDateTime API works with date and time parts to work with date operations.

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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 LocalDateTime Class With Examples
Java 8 LocalDateTime Class With Examples
A quick guide to LocalDateTime in java 8 with example programs. LocalDateTime API works with date and time parts to work with date operations.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjT_AurVbQ0stGxXXzN7TIkQO4juvfG2iM6Dop2Phi6AP4UBjs_peKtqM2j3AQUHuwyLidNRAMU_qKOseTVFQNGnYE32Znm5o-kMNHQ0A9dBV4wCXSSxRN9eMnze1CYmiYWDiJ-sLfcSR0/w640-h476/Java+8+LocalDateTime+Class+With+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjT_AurVbQ0stGxXXzN7TIkQO4juvfG2iM6Dop2Phi6AP4UBjs_peKtqM2j3AQUHuwyLidNRAMU_qKOseTVFQNGnYE32Znm5o-kMNHQ0A9dBV4wCXSSxRN9eMnze1CYmiYWDiJ-sLfcSR0/s72-w640-c-h476/Java+8+LocalDateTime+Class+With+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-8-localdatetime.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-8-localdatetime.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content