Get current date and time in Java

1. Get the current date

   在Java中,可以使用java.util.Date类和java.time.LocalDateTime类来获取系统当前的日期和时间。以下是两种常见的方法:
import java.util.Date;
Date date = new Date();
System.out.println(date);

In the above code, the current system time can be obtained by creating a Date object. The toString() method of the Date object returns a string representation of the current time.

2. Or get the current date and time

import java.time.LocalDateTime;

LocalDateTime now = LocalDateTime.now();
System.out.println(now);

In the above code, the current system date and time can be obtained by calling the static method now() of the LocalDateTime class. The toString() method of the LocalDateTime object returns a string representation of the current date and time.

It should be noted that the Date class and the LocalDateTime class represent time in slightly different ways. The Date class represents the number of milliseconds since midnight on January 1, 1970, while the LocalDateTime class provides more date and time manipulation methods.

Guess you like

Origin blog.csdn.net/weixin_52890053/article/details/133282897