How do you assign a value to a date type in Java?

In Java, you can assign values to the Date type using the following methods:

  1. Create a Date object representing the current date and time using the default constructor of the Date class.
Date currentDate = new Date();
  1. Create a Date object with a specified date and time using the parameterized constructor of the Date class. It accepts date and time values in milliseconds.
long milliseconds = 1635456000000L; // 毫秒数表示日期和时间(示例为2021年10月29日 00:00:00)
Date specificDate = new Date(milliseconds);
  1. Parse a string into a Date object using the SimpleDateFormat class. First, define the date format and then use the parse() method of the SimpleDateFormat class to parse the string into a Date object.
String dateString = "2021-10-29 00:00:00";
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date parsedDate = sdf.parse(dateString);

It is recommended to use the new date and time API from the java.time package when dealing with dates and times, which was introduced in Java 8. These new APIs offer more comprehensive and user-friendly methods for handling dates and times.

bannerAds