Guide to Java LocalDateTime

Learn about the LocalDateTime class in Java, how to create its instances and other use cases such as parsing, formatting and adding duration and periods.

1. Overview

java.time.LocalDateTime class, introduced in Java 8 Date Time API, represents a date and time object without a timezone often viewed as ‘year-month-day-hour-minute-second‘. It represents an instant in the local timeline to nanosecond precision e.g. 2007-12-03T10:15:30:55.000000.

We can use the LocalDateTime instances to represent the timestamps without any need for the timezone or offset reference. If we need a timestamp in a specific Zone then we should be using the ZonedDateTime instance.

For example, we can use LocalDateTime to trigger the batch jobs in any application. Jobs will be executed at a specific time in the timezone where the server is located.

Note that LocalDateTime instances are immutable and thread-safe. It is declared as below in the Java source code.

public final class LocalDateTime
	extends Object
	implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable
{
	//class body
}

2. Creating LocalDateTime

Generally, we will be creating LocalDateTime instances in two conditions i.e. get current timestamp or create local date-time for specified values.

2.1. Get Current Timestamp

Use the now() method to get the current local date-time. Note that we can get the current local timestamp in another zone by passing the zone id.

LocalDateTime now = LocalDateTime.now();

//Current timestamp in UTC
LocalDateTime utcTimestamp = LocalDateTime.now(ZoneId.of("UTC"));

2.2. Create LocalDateTime with Values

To create a local timestamp with a specific date and time information – use of(year, month, day, hour, minute, second, nanosecond) method that is an overloaded method with optional arguments.

//Nonoseconds precision
LocalDateTime localDateTime1 =
		LocalDateTime.of(2019, 03, 28, 14, 33, 48, 640000);

//Using Month Enum
LocalDateTime localDateTime2 =
		LocalDateTime.of(2019, Month.MARCH, 28, 14, 33, 48, 000000);

//Seconds level precision
LocalDateTime localDateTime3 =
		LocalDateTime.of(2019, Month.MARCH, 28, 14, 33, 48);

//Minutes level precision
LocalDateTime localDateTime4 =
		LocalDateTime.of(2019, Month.MARCH, 28, 14, 33);

2.3 Combine LocalDate and LocalTime

If we have separate instances of LocalDate and LocalTime classes, then we can combine them to obtain the instance of LocalDateTime.

//local date + local time
LocalDate date = LocalDate.of(2109, 03, 28);
LocalTime time = LocalTime.of(10, 34);	

LocalDateTime localDateTime5 = LocalDateTime.of(date, time);

3. Parsing a String to LocalDateTime

The LocalDateTime class has two overloaded parse() methods to convert time in the string to LocalDateTime instance.

parse(CharSequence text)	//1

parse(CharSequence text, DateTimeFormatter formatter)	//2
  • Use first method if the string contains time in ISO_LOCAL_DATE_TIME pattern i.e. 2019-03-27T10:15:30. This is default pattern of LocalDateTime in Java.
  • For any other date-time pattern, we need to use second method where we pass the time as string as well as a DateTimeFormatter which represents the pattern of that date-time string.
//1 - default time pattern
String time = "2019-03-27T10:15:30";
LocalDateTime localTimeObj = LocalDateTime.parse(time);

//2 - specific date time pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");
String time1 = "2019-03-27 10:15:30 AM";
LocalDateTime localTimeObj1 = LocalDateTime.parse(time1, formatter);

4. Formatting LocalDateTime

Use LocalDateTime.format(DateTimeFormatter) method to format a LocalDateTime to the desired string representation.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");

LocalDateTime now = LocalDateTime.now();

String dateTimeString = now.format(formatter);	//2019-03-28 14:47:33 PM

5. Modifying LocalDateTime

LocalDateTime provides below methods that can be used to get to new LocalDateTime instance relative to a given instance. These methods will help in adding and subtracting days to the given timestamp.

  • plusYears()
  • plusMonths()
  • plusDays()
  • plusHours()
  • plusMinutes()
  • plusSeconds()
  • plusNanos()
  • minusYears()
  • minusMonths()
  • minusDays()
  • minusHours()
  • minusMinutes()
  • minusSeconds()
  • minusNanos()
LocalDateTime now = LocalDateTime.now();

//3 hours later
LocalDateTime localDateTime1 = now.plusHours(3);	

//3 minutes earliar
LocalDateTime localDateTime2 = now.minusMinutes(3);

//Next year same time
LocalDateTime localDateTime2 = now.plusYears(1);

//Last year same time
LocalDateTime localDateTime2 = now.minusYears(1);

6. Conclusion

In this tutorial, we learned about the LocalDate class in Java. We learned to create the instances using factory methods and constructors. Then we learned the other use cases such as parsing and formatting the timestamps.

We also learned to add duration and periods to local timestamps.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.