How is LocalDateTime used in Java?
LocalDateTime is a date-time class introduced in Java 8 for representing an immutable date-time object without time zone information.
Here is how to use the LocalDateTime class:
- Create a LocalDateTime object.
- Get the current date and time with the LocalDateTime.now() method. Create a specific date and time using LocalDateTime.of() with the parameters (2021, 12, 31, 23, 59, 59). Parse a string into a LocalDateTime object with the LocalDateTime.parse() method.
- Get the various components of the date and time:
- year, month, dayOfMonth, hour, minute, and second are variables that store the current year, month, day of the month, hour, minute, and second respectively.
- Change different parts of the date and time.
- Modified date time is set to January 1st, 2022. Adding one day and two hours to the current date time. Subtracting one month and thirty minutes from the current date time.
- Compare the chronological order of dates and times.
- boolean isAfter = now.isAfter(specificDateTime); // Check if it’s after the specific date and time
boolean isBefore = now.isBefore(specificDateTime); // Check if it’s before the specific date and time - Format date and time as a string:
- Format the current date and time into a string using the specified pattern.
- Other common methods include:
- Truncate the current date and time to the nearest hour and obtain the start of the day for the current date.
Please note that the LocalDateTime class is immutable, any modification will return a new object.