YouTip LogoYouTip

Java Date Class

Java Date Class | Rookie Tutorial

\n\n

In Java, the Date class is located in the java.util package. It represents a specific instant in time, with millisecond precision.

\n\n

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\n

It 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
\n\n

Basic Usage of Date Class

\n\n

Creating Date Objects

\n\n

The Date class has multiple constructors, with the two most commonly used methods being:

\n\n

Example

\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\n

Common Methods

\n\n

The Date class provides several commonly used methods:

\n\n

Example

\n\n
Date 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\n

The Date class itself does not provide formatting functionality, but we can use the SimpleDateFormat class to format and parse dates.

\n\n

Date Formatting Example

\n\n

Example

\n\n
import 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\n

Output result:

\n\n
Format 1: 2025-05-01 11:33:43\nFormat 2: 2025Year05Month01Day Thursday 11Hour33Minute43Second
\n\n

Common Format Patterns

\n\n\n\n\n\n\n\n\n\n\n\n\n\n
LetterMeaningExample
yYearyyyy β†’ 2023
MMonthMM β†’ 01, MMM β†’ Jan
dDaydd β†’ 05
HHour (24-hour format)HH β†’ 13
hHour (12-hour format)hh β†’ 01
mMinutemm β†’ 30
sSecondss β†’ 45
SMillisecondSSS β†’ 789
EDay of weekE β†’ Monday
aAM/PM markera β†’ PM
\n\n

Comprehensive Example

\n\n

Here is a simple example of Date:

\n\n

Example

\n\n
import 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\n

Output result:

\n\n
Current 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\n

Although the Date class is still usable in many cases, it has some obvious limitations:

\n\n
    \n
  1. Not thread-safe: Date objects are mutable, which can cause problems in multi-threaded environments.
  2. \n
  3. Poor design: Months start from 0 (0 represents January), years are calculated from 1900, which can easily cause confusion.
  4. \n
  5. Complex timezone handling: The Date class itself does not contain timezone information; timezone handling requires additional classes.
  6. \n
  7. Limited functionality: Lacks many commonly used date operation functions, such as adding/subtracting days, weeks, etc.
  8. \n
\n\n
\n\n

Alternative: Java 8 Date-Time API

\n\n

Java 8 introduced a new date-time API (the java.time package), which solves many problems of the Date class:

\n\n

Example

\n\n
import 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\n

The new date-time API provides more features, such as:

\n\n
    \n
  • LocalDate - Contains only date
  • \n
  • LocalTime - Contains only time
  • \n
  • LocalDateTime - Contains both date and time
  • \n
  • ZonedDateTime - Contains date, time, and timezone
  • \n
  • Rich date manipulation methods
  • \n
\n\n
\n\n

Summary

\n\n
    \n
  1. The Date class is the basic class for representing dates and times in Java, but has some limitations.
  2. \n
  3. Use SimpleDateFormat to format and parse date strings.
  4. \n
  5. In Java 8 and above, it is recommended to use the new java.time API instead of the Date class.
  6. \n
  7. When maintaining old code, understanding the Date class is still important.
  8. \n
\n\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\n

Here are the commonly used methods of the java.util.Date class:

\n\n

Constructor Methods

\n\n\n\n\n\n
MethodDescriptionRemarks
Date()Creates a Date object representing the current timeDeprecated, recommended to use new Date() or Calendar.getInstance()
Date(long date)Creates a Date object based on the specified millisecondsMilliseconds are calculated from January 1, 1970, 00:00:00 GMT
\n\n

Common Methods

\n\n\n\n\n\n\n\n\n\n\n\n
MethodDescriptionRemarks
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 representationFormat like: "Tue Jun 22 13:07:00 CST 2021"
\n\n

Deprecated Methods (Not Recommended)

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
MethodDescriptionAlternative
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 monthUse Calendar.set(Calendar.DATE, date)
void setHours(int hours)Sets the hourUse Calendar.set(Calendar.HOUR_OF_DAY, hours)
void setMinutes(int minutes)Sets the minuteUse Calendar.set(Calendar.MINUTE, minutes)
void setMonth(int month)Sets the monthUse Calendar.set(Calendar.MONTH, month)
void setSeconds(int seconds)Sets the secondUse Calendar.set(Calendar.SECOND, seconds)
void setYear(int year)Sets the yearUse Calendar.set(Calendar.YEAR, year)
← Java Calendar ClassJava Regex Pattern β†’