Java Date Class
In Java,Datethe class is located injava.utilthe package, and it represents a specific instant, accurate to the millisecond.
The Date class is mainly used to represent date and time information, and is one of the basic classes for handling date and time in Java.
It should be noted that after Java 8, a new date-time API was introduced (java.timepackage). It isDatemore powerful and easier to use than the class. However, in many legacy codebases, you will still seeDateusage of the class.
Basic usage of the Date class
Creating a Date object
The Date class has multiple constructors; the two most commonly used ways are:
Example
Date currentDate = new Date();
// Create a Date object for a specified time (milliseconds since January 1, 1970 00:00:00 GMT)
Date specificDate = new Date(1640995200000L); // January 1, 2022 00:00:00 GMT
Common methods
The Date class provides several commonly used methods:
Example
// Get the number of milliseconds since January 1, 1970 00:00:00 GMT
long timeInMillis = date.getTime();
// Set the time (milliseconds since January 1, 1970 00:00:00 GMT)
date.setTime(1640995200000L);
// Compare two dates
Date anotherDate = new Date();
int result = date.compareTo(anotherDate); // Returns -1 if before, 0 if equal, 1 if after
// Check whether the date is after the specified date
boolean isAfter = date.after(anotherDate);
// Check whether the date is before the specified date
boolean isBefore = date.before(anotherDate);
Formatting the Date class
The Date class itself does not provide formatting functionality, but we can use theSimpleDateFormatclass to format and parse dates.
Date formatting example
Example
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date date = new Date();
// Create a formatter object
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat(yyyy-MM-dd E HH:mm:ss);
// Format the date
String formattedDate1 = sdf1.format(date);
String formattedDate2 = sdf2.format(date);
System.out.println("Format 1: " + formattedDate1);
System.out.println("Format 2: " + formattedDate2);
}
}
The output result is:
格式1: 2025-05-01 11:33:43 格式2: 2025年05月01日 周四 11时33分43秒
Common format patterns
| Letter | Meaning | Example |
|---|---|---|
| y | year | yyyy → 2023 |
| M | month | MM → 01, MMM → Jan |
| d | day | dd → 05 |
| H | Hour (24-hour) | HH → 13 |
| h | Hour (12-hour) | hh → 01 |
| m | Minute | mm → 30 |
| s | second | ss → 45 |
| S | Millisecond | SSS → 789 |
| E | Day of the week | E → Monday |
| a | AM/PM marker | a → PM |
Comprehensive example
The following is a simple example of Date:
Example
import java.text.SimpleDateFormat;
public class DateDemo {
public static void main(String[] args) {
// 1. Create a Date object representing the current time
Date now = new Date();
System.out.println("Current time: " + now);
// 2. Create a Date object for a specific time (deprecated, not recommended)
@SuppressWarnings("deprecation")
Date oldDate = new Date(123, 4, 15); // May 15, 2023 (month 0-11)
System.out.println("Specific date: " + oldDate);
// 3. Create a Date object using a timestamp (recommended)
Date dateFromTimestamp = new Date(1684131330000L); // 2023-05-15 10:15:30
System.out.println("Created from timestamp: " + dateFromTimestamp);
// 4. Format the date output
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(now);
System.out.println("Formatted date: " + formattedDate);
// 5. Parse a string into a Date
try {
Date parsedDate = sdf.parse("2023-05-15 10:30:00");
System.out.println("Parsed date: " + parsedDate);
} catch (Exception e) {
e.printStackTrace();
}
// 6. Get the timestamp
long timestamp = now.getTime();
System.out.println("Timestamp: " + timestamp);
// 7. Compare dates
System.out.println("Is now after dateFromTimestamp: " + now.after(dateFromTimestamp));
System.out.println("Is now before dateFromTimestamp: " + now.before(dateFromTimestamp));
}
}
The output result is:
当前时间: Thu May 01 11:33:05 CST 2025 特定日期: Mon May 15 00:00:00 CST 2023 从时间戳创建: Mon May 15 14:15:30 CST 2023 格式化日期: 2025-05-01 11:33:05 解析后的日期: Mon May 15 10:30:00 CST 2023 时间戳: 1746070385401 now 是否在 dateFromTimestamp 之后: true now 是否在 dateFromTimestamp 之前: false
Limitations of the Date class
Although the Date class is still usable in many cases, it has some obvious limitations:
- Not thread-safe: Date objects are mutable, which can cause problems in multithreaded environments.
- Poor design: Months start from 0 (0 means January), and years are counted from 1900, which is easy to confuse.
- Complex time zone handling: The Date class itself does not contain time zone information; time zone handling requires additional classes.
- Limited functionality: It lacks many common date manipulation features, such as adding or subtracting days, weeks, etc.
Alternative: Java 8 Date-Time API
Java 8 introduced a new date-time API (java.timepackage), which solves many problems of the Date class:
Example
import java.time.format.DateTimeFormatter;
public class NewDateTimeExample {
public static void main(String[] args) {
// Get the current date and time
LocalDateTime now = LocalDateTime.now();
// Format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("Current time: " + formattedDateTime);
}
}
The new date-time API provides more features, such as:
LocalDate- Contains date onlyLocalTime- Contains time onlyLocalDateTime- Contains date and timeZonedDateTime- Contains date, time, and time zone- Rich date manipulation methods
Summary
DateThe class is a basic class in Java for representing date and time, but it has some limitations.- Using
SimpleDateFormatcan format and parse date strings. - In Java 8 and above, it is recommended to use the new
java.timeAPI instead ofDatethe class. - When maintaining legacy code, understanding
Datethe class is still important.
If you are developing a new project, it is recommended to prioritize the new Java 8 date-time API, as it is more intuitive, powerful, and thread-safe.
The following are the common methods of the java.util.Date class:
Constructors
| Method | Description | Remarks |
|---|---|---|
Date() |
Create a Date object representing the current time | Deprecated, it is recommended to usenew Date()orCalendar.getInstance() |
Date(long date) |
Create a Date object based on the specified number of milliseconds | The number of milliseconds is calculated from January 1, 1970 00:00:00 GMT |
Common methods
| Method | Description | Remarks |
|---|---|---|
boolean after(Date when) |
Tests whether this date is after the specified date | |
boolean before(Date when) |
Tests whether this date is before the specified date | |
Object clone() |
Returns a copy of this object | |
int compareTo(Date anotherDate) |
Compares the order of two dates | |
boolean equals(Object obj) |
Compares two dates for equality | |
long getTime() |
Returns the number of milliseconds since January 1, 1970 | |
void setTime(long time) |
Sets this Date object using a millisecond value | |
String toString() |
Converts the Date object to a string representation | Format example: "Tue Jun 22 13:07:00 CST 2021" |
Deprecated methods (not recommended)
| Method | Description | Replacement |
|---|---|---|
int getDate() |
Get the day of the month (1-31) | UseCalendar.get(Calendar.DATE) |
int getDay() |
Get the day of the week (0-6) | UseCalendar.get(Calendar.DAY_OF_WEEK) |
int getHours() |
Get the hour (0-23) | UseCalendar.get(Calendar.HOUR_OF_DAY) |
int getMinutes() |
Get the minute (0-59) | UseCalendar.get(Calendar.MINUTE) |
int getMonth() |
Get the month (0-11) | UseCalendar.get(Calendar.MONTH) |
int getSeconds() |
Get the seconds (0-59) | UseCalendar.get(Calendar.SECOND) |
int getYear() |
Get the year (starting from 1900) | UseCalendar.get(Calendar.YEAR) |
void setDate(int date) |
Set the day of the month | UseCalendar.set(Calendar.DATE, date) |
void setHours(int hours) |
Set the hour | UseCalendar.set(Calendar.HOUR_OF_DAY, hours) |
void setMinutes(int minutes) |
Set the minute | UseCalendar.set(Calendar.MINUTE, minutes) |
void setMonth(int month) |
Set the month | UseCalendar.set(Calendar.MONTH, month) |
void setSeconds(int seconds) |
Set the seconds | UseCalendar.set(Calendar.SECOND, seconds) |
void setYear(int year) |
Set the year | UseCalendar.set(Calendar.YEAR, year) |