Java Date Class | Rookie Tutorial
\n\nIn Java, the Date class is located in the java.util package. It represents a specific instant in time, with millisecond precision.
The Date class is mainly used to represent date and time information, and is one of the basic classes for handling dates and times in Java.
\n\nIt should be noted that after Java 8, a new date and time API was introduced (the java.time package), which is more powerful and easier to use than the Date class. However, in much legacy code, you will still see the use of the Date class.
\n\n
Basic Usage of Date Class
\n\nCreating Date Objects
\n\nThe Date class has multiple constructors, with the two most commonly used methods being:
\n\nExample
\n\n// Create a Date object representing the current time\nDate currentDate = new Date();\n\n// Create a Date object for a specific time (milliseconds since January 1, 1970, 00:00:00 GMT)\nDate specificDate = new Date(1640995200000L); // January 1, 2022, 00:00:00 GMT\n\nCommon Methods
\n\nThe Date class provides several commonly used methods:
\n\nExample
\n\nDate date = new Date();\n\n// Get milliseconds since January 1, 1970, 00:00:00 GMT\nlong timeInMillis = date.getTime();\n\n// Set time (milliseconds since January 1, 1970, 00:00:00 GMT)\ndate.setTime(1640995200000L);\n\n// Compare two dates\nDate anotherDate = new Date();\nint result = date.compareTo(anotherDate); // Returns -1 if less, 0 if equal, 1 if greater\n\n// Check if date is after the specified date\nboolean isAfter = date.after(anotherDate);\n\n// Check if date is before the specified date\nboolean isBefore = date.before(anotherDate);\n\n\n\n
Formatting Date Class
\n\nThe Date class itself does not provide formatting functionality, but we can use the SimpleDateFormat class to format and parse dates.
Date Formatting Example
\n\nExample
\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class DateFormatExample {\n public static void main(String[] args) {\n Date date = new Date();\n \n // Create formatting objects\n SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\n SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyYearMMMonthddDay E HHHourmmMinutessSecond");\n \n // Format dates\n String formattedDate1 = sdf1.format(date);\n String formattedDate2 = sdf2.format(date);\n \n System.out.println("Format 1: " + formattedDate1);\n System.out.println("Format 2: " + formattedDate2);\n }\n}\n\nOutput result:
\n\nFormat 1: 2025-05-01 11:33:43\nFormat 2: 2025Year05Month01Day Thursday 11Hour33Minute43Second\n\n
Common Format Patterns
\n\n| Letter | Meaning | Example |
|---|---|---|
| y | Year | yyyy β 2023 |
| M | Month | MM β 01, MMM β Jan |
| d | Day | dd β 05 |
| H | Hour (24-hour format) | HH β 13 |
| h | Hour (12-hour format) | hh β 01 |
| m | Minute | mm β 30 |
| s | Second | ss β 45 |
| S | Millisecond | SSS β 789 |
| E | Day of week | E β Monday |
| a | AM/PM marker | a β PM |
Comprehensive Example
\n\nHere is a simple example of Date:
\n\nExample
\n\nimport java.util.Date;\nimport java.text.SimpleDateFormat;\n\npublic class DateDemo {\n public static void main(String[] args) {\n // 1. Create a Date object representing the current time\n Date now = new Date();\n System.out.println("Current time: " + now);\n \n // 2. Create a Date object for a specific time (deprecated method, not recommended)\n @SuppressWarnings("deprecation")\n Date oldDate = new Date(123, 4, 15); // May 15, 2023 (months 0-11)\n System.out.println("Specific date: " + oldDate);\n \n // 3. Create Date object using timestamp (recommended method)\n Date dateFromTimestamp = new Date(1684131330000L); // 2023-05-15 10:15:30\n System.out.println("Created from timestamp: " + dateFromTimestamp);\n \n // 4. Format date output\n SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\n String formattedDate = sdf.format(now);\n System.out.println("Formatted date: " + formattedDate);\n \n // 5. Parse string to Date\n try {\n Date parsedDate = sdf.parse("2023-05-15 10:30:00");\n System.out.println("Parsed date: " + parsedDate);\n } catch (Exception e) {\n e.printStackTrace();\n }\n \n // 6. Get timestamp\n long timestamp = now.getTime();\n System.out.println("Timestamp: " + timestamp);\n \n // 7. Date comparison\n System.out.println("Is now after dateFromTimestamp: " + now.after(dateFromTimestamp));\n System.out.println("Is now before dateFromTimestamp: " + now.before(dateFromTimestamp));\n }\n}\n\nOutput result:
\n\nCurrent time: Thu May 01 11:33:05 CST 2025\nSpecific date: Mon May 15 00:00:00 CST 2023\nCreated from timestamp: Mon May 15 14:15:30 CST 2023\nFormatted date: 2025-05-01 11:33:05\nParsed date: Mon May 15 10:30:00 CST 2023\nTimestamp: 1746070385401\nIs now after dateFromTimestamp: true\nIs now before dateFromTimestamp: false\n\n
\n\n
Limitations of Date Class
\n\nAlthough the Date class is still usable in many cases, it has some obvious limitations:
\n\n- \n
- Not thread-safe: Date objects are mutable, which can cause problems in multi-threaded environments. \n
- Poor design: Months start from 0 (0 represents January), years are calculated from 1900, which can easily cause confusion. \n
- Complex timezone handling: The Date class itself does not contain timezone information; timezone handling requires additional classes. \n
- Limited functionality: Lacks many commonly used date operation functions, such as adding/subtracting days, weeks, etc. \n
\n\n
Alternative: Java 8 Date-Time API
\n\nJava 8 introduced a new date-time API (the java.time package), which solves many problems of the Date class:
Example
\n\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class NewDateTimeExample {\n public static void main(String[] args) {\n // Get current date and time\n LocalDateTime now = LocalDateTime.now();\n \n // Format\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");\n String formattedDateTime = now.format(formatter);\n \n System.out.println("Current time: " + formattedDateTime);\n }\n}\n\nThe new date-time API provides more features, such as:
\n\n- \n
LocalDate- Contains only date \nLocalTime- Contains only time \nLocalDateTime- Contains both date and time \nZonedDateTime- Contains date, time, and timezone \n- Rich date manipulation methods \n
\n\n
Summary
\n\n- \n
- The
Dateclass is the basic class for representing dates and times in Java, but has some limitations. \n - Use
SimpleDateFormatto format and parse date strings. \n - In Java 8 and above, it is recommended to use the new
java.timeAPI instead of theDateclass. \n - When maintaining old code, understanding the
Dateclass is still important. \n
If you are developing a new project, it is recommended to prioritize using Java 8's new date-time API, which is more intuitive, powerful, and thread-safe.
\n\nHere are the commonly used methods of the java.util.Date class:
\n\nConstructor Methods
\n\n| Method | Description | Remarks |
|---|---|---|
Date() | Creates a Date object representing the current time | Deprecated, recommended to use new Date() or Calendar.getInstance() |
Date(long date) | Creates a Date object based on the specified milliseconds | Milliseconds are calculated from January 1, 1970, 00:00:00 GMT |
Common Methods
\n\n| Method | Description | Remarks |
|---|---|---|
boolean after(Date when) | Tests if this date is after the specified date | |
boolean before(Date when) | Tests if 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 the equality of two dates | |
long getTime() | Returns milliseconds since January 1, 1970 | |
void setTime(long time) | Sets this Date object using milliseconds | |
String toString() | Converts Date object to string representation | Format like: "Tue Jun 22 13:07:00 CST 2021" |
Deprecated Methods (Not Recommended)
\n\n| Method | Description | Alternative |
|---|---|---|
int getDate() | Gets the day of the month (1-31) | Use Calendar.get(Calendar.DATE) |
int getDay() | Gets the day of the week (0-6) | Use Calendar.get(Calendar.DAY_OF_WEEK) |
int getHours() | Gets the hour (0-23) | Use Calendar.get(Calendar.HOUR_OF_DAY) |
int getMinutes() | Gets the minute (0-59) | Use Calendar.get(Calendar.MINUTE) |
int getMonth() | Gets the month (0-11) | Use Calendar.get(Calendar.MONTH) |
int getSeconds() | Gets the second (0-59) | Use Calendar.get(Calendar.SECOND) |
int getYear() | Gets the year (starting from 1900) | Use Calendar.get(Calendar.YEAR) |
void setDate(int date) | Sets the day of the month | Use Calendar.set(Calendar.DATE, date) |
void setHours(int hours) | Sets the hour | Use Calendar.set(Calendar.HOUR_OF_DAY, hours) |
void setMinutes(int minutes) | Sets the minute | Use Calendar.set(Calendar.MINUTE, minutes) |
void setMonth(int month) | Sets the month | Use Calendar.set(Calendar.MONTH, month) |
void setSeconds(int seconds) | Sets the second | Use Calendar.set(Calendar.SECOND, seconds) |
void setYear(int year) | Sets the year | Use Calendar.set(Calendar.YEAR, year) |
YouTip