How to create a date object in Java?
In Java, you can use the java.util.Date class to create date objects. There are several commonly used methods for this.
- Create a current date object using a parameterless constructor.
- Create a new object called “date” of type Date.
- Create a date object with a specified timestamp.
- Create a new Date object using the current timestamp obtained from the system.
- Create a date object with the specified year, month (0-11), date, hour, minutes, and seconds.
- Create a new date object representing January 1, 2022 at midnight.
It’s important to note that the java.util.Date class has been deprecated in Java 8 and above, and it is recommended to use the new date-time API in the java.time package. For instance, you can use the java.time.LocalDate class to create date objects.
import java.time.LocalDate;
LocalDate date = LocalDate.now(); // 当前日期
LocalDate customDate = LocalDate.of(2022, 1, 1); // 自定义日期