📜  java localtime - Java (1)

📅  最后修改于: 2023-12-03 15:15:56.876000             🧑  作者: Mango

Java LocalDateTime

Java LocalDateTime is a class in the Java 8 Date Time API that represents a date and time without any timezone information. It is one of the most commonly used classes for working with dates and times in Java.

Creating a LocalDateTime Object

To create a LocalDateTime object, use the now() method to get the current date and time or use the of() method to create a new instance with a specific date and time.

// Get the current date and time
LocalDateTime now = LocalDateTime.now();

// Create a LocalDateTime object with a specific date and time
LocalDateTime dateTime = LocalDateTime.of(2021, 7, 21, 10, 30, 0);
Formatting a LocalDateTime Object

To format a LocalDateTime object into a string, use the format() method along with a DateTimeFormatter object.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime); // Output: 2021-07-21 10:30:00
Manipulating a LocalDateTime Object

You can manipulate a LocalDateTime object using various methods provided by the class such as plus(), minus(), and with().

// Add 1 day to the date
LocalDateTime newDateTime = dateTime.plusDays(1);

// Subtract 2 hours from the time
newDateTime = newDateTime.minusHours(2);

// Set the year to 2022
newDateTime = newDateTime.withYear(2022);
Comparing LocalDateTime Objects

You can compare two LocalDateTime objects using the compareTo() method.

if(dateTime.compareTo(now) < 0) {
    System.out.println("dateTime is before now");
} else if(dateTime.compareTo(now) > 0) {
    System.out.println("dateTime is after now");
} else {
    System.out.println("dateTime is the same as now");
}
Conclusion

In conclusion, the Java LocalDateTime class is a powerful tool for working with dates and times in Java. It allows you to create, format, manipulate, and compare LocalDateTime objects with ease.