Java LocalDateTime
The Java LocalDateTime class is an immutable and thread-safe class that represents date and time with a default format of yyyy-MM-dd-HH-mm-ss.zzz. The LocalDateTime class can be used to store date and time in the following format “22nd April 2018 at 05:10.30.123456789”.
How to use
This class does not handle or represent time-zone, we can use LocalDateTime class to store information like birthdays with time. Try the below-shown examples, it will print the date and time according to your system default zone. The time might be different if you run the code in our online Java Editor as the code is running on somewhere in the cloud.
Parsing example
The following example program shows how you can parse date and time from a given string.
import java.time.LocalDateTime; public class LocalDateTimeExample1 { public static void main(String[] args) { // Get current date and time LocalDateTime dateTime = LocalDateTime.now(); System.out.println("Current date & time: " + dateTime); // Parsing given date and time dateTime = LocalDateTime.parse("2019-05-06T11:57:27.866003800"); System.out.println("Parsed date & time: " + dateTime); } }
Format example
The following example program shows how you can format date & time.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeExample2 { public static void main(String[] args) { // Get current date and time LocalDateTime dateTime = LocalDateTime.now(); System.out.println("Default format: " + dateTime); // Format date & time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss"); String formated = dateTime.format(formatter); System.out.println("Formatted date & time: " + formated); } }
Fields example
The following example program shows how you can get different fields of date & time.
import java.time.LocalDateTime; public class LocalDateTimeExample3 { public static void main(String[] args) { // Get current date and time LocalDateTime dateTime = LocalDateTime.now(); // Get different fields of date and time System.out.println("Year: " + dateTime.getYear()); System.out.println("Month: " + dateTime.getMonth()); System.out.println("Day: " + dateTime.getDayOfMonth()); System.out.println("Hour: " + dateTime.getHour()); System.out.println("Minute: " + dateTime.getMinute()); System.out.println("Second: " + dateTime.getSecond()); } }