Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Date Class · Private Archive

Java Date Class · Private Archive

Java Date Class Date The java.util class is located in

package; 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 dates and times in Java.java.time Note that after Java 8, a new date-time API ( Date package) was introduced, which is more powerful and easier to use than the Date class. But in many legacy codes, you will still see the


class in use.

Basic Usage of the Date Class

Create a Date Object

Example

The Date class has multiple constructors; the two most commonly used ways are:

Date

currentDate

=

new

Date

(

)

;

// Create a Date object representing the current time

Date

specificDate

=

new

Date

(

1640995200000L

)

;

// Create a Date object for a specified time (milliseconds since 00:00:00 GMT, January 1, 1970)

// 2022-01-01 00:00:00 GMT

Common Methods

Example

Date

date

=

new

Date

(

)

;

The Date class provides several commonly used methods:

long

timeInMillis

=

date.

getTime

(

)

;

// Get milliseconds since 00:00:00 GMT, January 1, 1970

date.

setTime

(

1640995200000L

)

;

// Set time (milliseconds since 00:00:00 GMT, January 1, 1970)

Date

anotherDate

=

new

Date

(

)

;

int

result

=

date.

compareTo

(

anotherDate

)

;

// Compare two dates

// Less than returns -1, equal returns 0, greater than returns 1

boolean

isAfter

=

date.

after

(

anotherDate

)

;

// Check whether the date is after a specified date

boolean

isBefore

=

date.

before

(

anotherDate

)

;


// Check whether the date is before a specified date

Formatting the Date Class SimpleDateFormat The Date class itself does not provide formatting functionality, but we can use the

class to format and parse dates.

Example

import

java.text.SimpleDateFormat

;

import

java.util.Date

;

public

class

DateFormatExample

{

   

public

static

void

main

(

String

[

]

args

)

{

       

Date

date

=

new

Date

(

)

;

       

       

Date Formatting Example

       

SimpleDateFormat

sdf1

=

new

SimpleDateFormat

(

"yyyy-MM-dd HH:mm:ss"

)

;

       

SimpleDateFormat

sdf2

=

new

SimpleDateFormat

(

// Create a formatting object

)

;

       

       

"yyyy-MM-dd E HH:mm:ss"

       

String

formattedDate1

=

sdf1.

format

(

date

)

;

       

String

formattedDate2

=

sdf2.

format

(

date

)

;

       

       

System

.

out

.

println

(

// Format the date

formattedDate1

)

;

       

System

.

out

.

println

(

"Format 1: "

formattedDate2

)

;

   

}

}

The output is:

格式1: 2025-05-01 11:33:43
格式2: 2025年05月01日 周四 11时33分43秒

"Format 2: "

Common Format Patterns Meaning Example
y Year yyyy → 2023
M Month MM → 01, MMM → Jan
d Day dd → 05
H Letter HH → 13
h Hour (24-hour) hh → 01
m Minute mm → 30
s Second ss → 45
S Millisecond SSS → 789
E Week Hour (12-hour)
a E → Monday AM/PM marker

Comprehensive example

a → PM

Example

import

java.util.Date

;

import

java.text.SimpleDateFormat

;

public

class

DateDemo

{

   

public

static

void

main

(

String

[

]

args

)

{

       

The following is a simple example of Date:

       

Date

now

=

new

Date

(

)

;

       

System

.

out

.

println

(

Current time:

now

)

;

       

       

// 1. Create a Date object representing the current time

        @SuppressWarnings

(

"deprecation"

)

       

Date

oldDate

=

new

Date

(

123

,

4

,

15

)

;

// 2. Create a Date object for a specific time (deprecated method, not recommended)

       

System

.

out

.

println

(

// 2023-05-15 (month 0-11)

oldDate

)

;

       

       

"Specific date: "

       

Date

dateFromTimestamp

=

new

Date

(

1684131330000L

)

;

// 2023-05-15 10:15:30

       

System

.

out

.

println

(

// 3. Use a timestamp to create a Date object (recommended way)

dateFromTimestamp

)

;

       

       

"Created from timestamp: "

       

SimpleDateFormat

sdf

=

new

SimpleDateFormat

(

"yyyy-MM-dd HH:mm:ss"

)

;

       

String

formattedDate

=

sdf.

format

(

now

)

;

       

System

.

out

.

println

(

// 4. Format date output

formattedDate

)

;

       

       

"Formatted date: "

       

try

{

           

Date

parsedDate

=

sdf.

parse

(

"2023-05-15 10:30:00"

)

;

           

System

.

out

.

println

(

// 5. Parse a string into a Date

parsedDate

)

;

       

}

catch

(

Exception

e

)

{

            e.

printStackTrace

(

)

;

       

}

       

       

"Parsed date: "

       

long

timestamp

=

now.

getTime

(

)

;

       

System

.

out

.

println

(

// 6. Get timestamp

timestamp

)

;

       

       

"Timestamp: "

       

System

.

out

.

println

(

// 7. Date comparison

now.

after

(

dateFromTimestamp

)

)

;

       

System

.

out

.

println

(

"Is now after dateFromTimestamp: "

now.

before

(

dateFromTimestamp

)

)

;

   

}

}

The output 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

"Is now before dateFromTimestamp: "

Limitations of the Date Class

  1. Although the Date class is still usable in many cases, it has some obvious limitations:Not thread-safe
  2. : Date objects are mutable, which may cause problems in multi-threaded environments.Poor design
  3. : The month starts from 0 (0 means January), and the year is calculated from 1900, which can easily cause confusion.Complex time zone handling
  4. : The Date class itself does not contain time zone information; time zone handling requires additional classes.Limited functionality

: Lacks many common date operation functions, such as adding/subtracting days, weeks, etc.

Alternative: Java 8 Date-Time APIjava.time Java 8 introduced a new date-time API (

Example

import

java.time.LocalDateTime

;

import

java.time.format.DateTimeFormatter

;

public

class

NewDateTimeExample

{

   

public

static

void

main

(

String

[

]

args

)

{

       

package), which solves many problems of the Date class:

        LocalDateTime now

=

LocalDateTime.

now

(

)

;

       

       

// Get current date and time

        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 functions, such as:


Summary

  1. Date The class is the fundamental class in Java for representing dates and times, but it has some limitations.
  2. Use SimpleDateFormat It can format and parse date strings.
  3. In Java 8 and above, it is recommended to use the new java.time API instead Date class.
  4. When maintaining legacy code, understanding Date the class is still important.

If you are developing a new project, it is recommended to prioritize using the new Java 8 Date and Time API, which is more intuitive, powerful, and thread-safe.

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

Constructor

Method Description Notes
Date() Creates a Date object representing the current time Deprecated; it is recommended to usenew Date()orCalendar.getInstance()
Date(long date) Creates a Date object based on the specified number of milliseconds The milliseconds are counted from 00:00:00 GMT on January 1, 1970

// 2022-01-01 00:00:00 GMT

Method Description Notes
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 the equality of two dates
long getTime() Returns the number of milliseconds since January 1, 1970
void setTime(long time) Sets this Date object using the number of milliseconds
String toString() Converts the Date object into a string representation Format example: "Tue Jun 22 13:07:00 CST 2021"

Deprecated methods (not recommended)

Method Description Alternatives
int getDate() Gets the day of the month (1-31) UseCalendar.get(Calendar.DATE)
int getDay() Gets the day of the week (0-6) UseCalendar.get(Calendar.DAY_OF_WEEK)
int getHours() Gets the hour (0-23) UseCalendar.get(Calendar.HOUR_OF_DAY)
int getMinutes() Gets the minutes (0-59) UseCalendar.get(Calendar.MINUTE)
int getMonth() Gets the month (0-11) UseCalendar.get(Calendar.MONTH)
int getSeconds() Gets the seconds (0-59) UseCalendar.get(Calendar.SECOND)
int getYear() Gets the year (starting from 1900) UseCalendar.get(Calendar.YEAR)
void setDate(int date) Sets the day of the month UseCalendar.set(Calendar.DATE, date)
void setHours(int hours) Sets the hour UseCalendar.set(Calendar.HOUR_OF_DAY, hours)
void setMinutes(int minutes) Sets the minutes UseCalendar.set(Calendar.MINUTE, minutes)
void setMonth(int month) Sets the month UseCalendar.set(Calendar.MONTH, month)
void setSeconds(int seconds) Sets the seconds UseCalendar.set(Calendar.SECOND, seconds)
void setYear(int year) Sets the year UseCalendar.set(Calendar.YEAR, year)