How to define a date in Java?
In Java, you can define dates using the java.util.Date class and java.util.Calendar class.
- A Date object in the java.util package
- Date class in Java
- – Appointment
– Meeting
– Rendezvous - – Time and day of the month
- – The specified day
import java.util.Date;
// 创建当前时间的Date对象
Date currentDate = new Date();
// 创建指定时间的Date对象
Date specifiedDate = new Date(2022, 11, 31, 23, 59, 59);
- The Calendar class in the java.util package
- The Calendar class from the Java utility package.
- Get the current instance of the Calendar.
- Schedule
- create a collection without duplicate elements
import java.util.Calendar;
// 创建一个Calendar对象
Calendar calendar = Calendar.getInstance();
// 设置日期的年、月、日
calendar.set(Calendar.YEAR, 2022);
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 31);
// 获取设置后的日期
Date date = calendar.getTime();
It should be noted that most methods in the java.util.Date class have been marked as deprecated, and it is recommended to use the new date and time API in the java.time package, such as java.time.LocalDate, java.time.LocalDateTime, etc. Since Java 8, a new date and time API has been introduced, providing better design and usability.