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.

  1. Create a current date object using a parameterless constructor.
  2. Create a new object called “date” of type Date.
  3. Create a date object with a specified timestamp.
  4. Create a new Date object using the current timestamp obtained from the system.
  5. Create a date object with the specified year, month (0-11), date, hour, minutes, and seconds.
  6. 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); // 自定义日期
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds