Java Date Time
Java provides multiple date and time APIs. The following is a comparison of the main categories and a summary of common methods:
| Category | Main Classes | Thread-safe | Mutability | Java Version | Features |
|---|---|---|---|---|---|
| Legacy Date | Date, Calendar,GregorianCalendar | no | Mutable | 1.0+ | Many design flaws, not recommended |
| New Date Time | LocalDate, LocalTime, LocalDateTime, ZonedDateTime, ChronoUnit | Yes | Immutable | 8+ | Well-designed, recommended |
| Timestamp | Instant | Yes | Immutable | 8+ | Machine time, accurate to nanoseconds |
| Formatting | DateTimeFormatter | Yes | Immutable | 8+ | Thread-safe formatting class |
LocalDate/DateTimeFormatter
LocalDate/DateTimeFormatter are date classes introduced in Java 8. LocalDate is used to represent a date without time (year-month-day), and DateTimeFormatter is used to format and parse date-time objects.
Example
import java.time.format.DateTimeFormatter;
public class ExampleTest {
public static void main(String[] args) {
// Get current date
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
// Create a specific date
LocalDate nationalDay = LocalDate.of(2025, 10, 1);
System.out.println("National Day: " + nationalDay);
// Date addition and subtraction
LocalDate tomorrow = today.plusDays(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate lastYear = today.minusYears(1);
System.out.println("Tomorrow: " + tomorrow);
System.out.println("Next month: " + nextMonth);
System.out.println("Same day last year: " + lastYear);
}
}
The output of the above example is:
当前日期: 2025-05-01 国庆节: 2025-10-01 明天: 2025-05-02 下个月: 2025-06-01 去年今天: 2024-05-01
-
New projects should prefer the java.time package (Java 8+)
-
Avoid using the legacy Date and Calendar classes
-
Clearly distinguish time zone usage:
-
No time zone needed: LocalDate/LocalTime/LocalDateTime
-
Time zone needed: ZonedDateTime
-
-
Consider thread safety when formatting: Use DateTimeFormatter instead of SimpleDateFormat
-
Database interaction:
-
JDBC 4.2+ natively supports java.time types
-
Older versions can convert to java.sql.Date/Timestamp
-
1. LocalDate (Date)
Example
LocalDate date = LocalDate.of(2023, Month.JUNE, 15);
int year = date.getYear(); // 2023
Month month = date.getMonth(); // JUNE
int day = date.getDayOfMonth(); // 15
LocalDate nextWeek = today.plusWeeks(1);
boolean isLeap = date.isLeapYear(); // Is it a leap year
2. LocalTime (Time)
Example
LocalTime time = LocalTime.of(14, 30, 45); // 14:30:45
int hour = time.getHour(); // 14
int minute = time.getMinute(); // 30
LocalTime nextHour = time.plusHours(1);
3. LocalDateTime (Date and Time)
Example
LocalDateTime dt = LocalDateTime.of(2023, 6, 15, 14, 30);
LocalDateTime nextMonth = dt.plusMonths(1);
4. ZonedDateTime (Date and Time with Time Zone)
Example
ZonedDateTime nyTime = zdt.withZoneSameInstant(ZoneId.of("America/New_York"));
ZoneId zone = zdt.getZone(); // Get time zone
5. Instant (Timestamp)
Example
Instant later = now.plusSeconds(60); // 60 seconds later
long epochMilli = now.toEpochMilli(); // Get millisecond timestamp
Date Class
The java.util package provides the Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate Date objects.
The first constructor initializes the object with the current date and time.
The second constructor accepts a parameter, which is the number of milliseconds since January 1, 1970.
After a Date object is created, the following methods can be called.
| No. | Methods and Description |
|---|---|
| 1 |
boolean after(Date date) Returns true if the Date object that calls this method is after the specified date; otherwise returns false. |
| 2 |
boolean before(Date date) Returns true if the Date object that calls this method is before the specified date; otherwise returns false. |
| 3 |
Object clone( ) Returns a copy of this object. |
| 4 |
int compareTo(Date date) Compares the Date object that calls this method with the specified date. Returns 0 when both are equal. Returns a negative number if the calling object is before the specified date. Returns a positive number if the calling object is after the specified date. |
| 5 |
int compareTo(Object obj) If obj is of type Date, the operation is equivalent to compareTo(Date). Otherwise it throws a ClassCastException. |
| 6 |
boolean equals(Object date) Returns true when the Date object that calls this method is equal to the specified date; otherwise returns false. |
| 7 |
long getTime( ) Returns the number of milliseconds represented by this Date object since January 1, 1970, 00:00:00 GMT. |
| 8 |
int hashCode( ) Returns the hash code value of this object. |
| 9 |
void setTime(long time) Sets the time and date using the number of milliseconds since January 1, 1970, 00:00:00 GMT. |
| 10 |
String toString( ) Converts this Date object to a String of the form: dow mon dd hh:mm:ss zzz yyyy, where: dow is a day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat). |
Get Current Date and Time
Getting the current date and time in Java is simple, using the toString() method of the Date object to print the current date and time, as shown below:
Example
Run Example »
The result of compiling and running the above example is as follows:
Mon May 04 09:51:52 CDT 2013
Date Comparison
Java uses the following three methods to compare two dates:
- Use the getTime() method to obtain two dates (the number of milliseconds elapsed since January 1, 1970), then compare these two values.
- Use the methods before(), after(), and equals(). For example, the 12th of a month is earlier than the 18th, thennew Date(99, 2, 12).before(new Date (99, 2, 18))returns true.
- Use the compareTo() method, which is defined by the Comparable interface, and the Date class implements this interface.
1. Compare using getTime() method
This method compares dates by comparing the number of milliseconds since January 1, 1970 (Unix epoch) of the date objects.
Example
public class DateComparison {
public static void main(String[] args) {
Date date1 = new Date(121, 5, 15); // June 15, 2021
Date date2 = new Date(121, 5, 20); // June 20, 2021
// Compare milliseconds
if (date1.getTime() < date2.getTime()) {
System.out.println("date1 is before date2");
} else if (date1.getTime() > date2.getTime()) {
System.out.println("date1 is after date2");
} else {
System.out.println("The two dates are the same");
}
}
}
Output:
date1 在 date2 之前
2. Use before(), after() and equals() methods
These methods are built-in comparison methods of the Date class, with clearer semantics.
Example
public class DateComparison {
public static void main(String[] args) {
Date date1 = new Date(121, 5, 15); // June 15, 2021
Date date2 = new Date(121, 5, 20); // June 20, 2021
// Use before() method
System.out.println("Is date1 before date2? " + date1.before(date2));
// Use after() method
System.out.println("Is date1 after date2? " + date1.after(date2));
// Use equals() method
System.out.println("Are the two dates the same? " + date1.equals(date2));
}
}
Output:
date1 在 date2 之前吗? true date1 在 date2 之后吗? false 两个日期相同吗? false
3. Use compareTo() method
The Date class implements the Comparable interface and can be compared using the compareTo() method.
Example
public class DateComparison {
public static void main(String[] args) {
Date date1 = new Date(121, 5, 15); // June 15, 2021
Date date2 = new Date(121, 5, 20); // June 20, 2021
int result = date1.compareTo(date2);
if (result < 0) {
System.out.println("date1 is before date2");
} else if (result > 0) {
System.out.println("date1 is after date2");
} else {
System.out.println("The two dates are the same");
}
}
}
Output:
date1 在 date2 之前
Formatting Dates Using SimpleDateFormat
SimpleDateFormat is a class that formats and parses dates in a locale-sensitive manner. SimpleDateFormat allows you to choose any user-defined date-time format to run. For example:
Example
Run example »
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
This line of code establishes the conversion format, where yyyy is the full year, MM is the month, dd is the day, and HH:mm:ss is the hour, minute, and second.
Note: Some formats are uppercase and some are lowercase; for example, MM is month, mm is minutes; HH is 24-hour format, while hh is 12-hour format.
The result of compiling and running the above example is as follows:
当前时间为: 2018-09-06 10:16:34
Date and Time Formatting Codes
The time pattern string is used to specify the time format. In this pattern, all ASCII letters are reserved as pattern letters, defined as follows:
| Letter | Description | Example |
|---|---|---|
| G | Era marker | AD |
| y | Four-digit year | 2001 |
| M | Month | July or 07 |
| d | Day of month | 10 |
| h | Hour in A.M./P.M. (1~12) format | 12 |
| H | Hour of day (0~23) | 22 |
| m | Minutes | 30 |
| s | Seconds | 55 |
| S | Milliseconds | 234 |
| E | Day of week | Tuesday |
| D | Day of year | 360 |
| F | Day of week in month | 2 (second Wed. in July) |
| w | Week in year | 40 |
| W | Week in month | 1 |
| a | A.M./P.M. marker | PM |
| k | Hour of day (1~24) | 24 |
| K | Hour in A.M./P.M. (0~11) format | 10 |
| z | Time zone | Eastern Standard Time |
| ' | Text delimiter | Delimiter |
| " | Single quote | ` |
Formatting Dates Using printf
The printf method can format time and date very easily. Using a two-letter format, it starts with%t%t and ends with one of the letters in the table below.
- %tY: Outputs a four-digit year, for example: 2023
- %ty: Outputs a two-digit year, for example: 23
- %tm: Outputs a two-digit month, for example: 02
- %tB: Outputs the full name of the month, for example: February
- %tb: Outputs the abbreviation of the month, for example: Feb
- %tA: Outputs the full name of the day of the week, for example: Wednesday
- %ta: Outputs the abbreviation of the day of the week, for example: Wed
- %td: Outputs a two-digit day, for example: 24
- %te: Outputs a one- or two-digit day, for example: 24 or 02
- %tH: Outputs the hour in 24-hour format, for example: 23
- %tI: Outputs the hour in 12-hour format, for example: 11
- %tM: Outputs the minutes, for example: 45
- %tS: Outputs the seconds, for example: 30
- %tp: Outputs morning or afternoon, for example: AM or PM
- %tZ: Outputs the time zone, for example: GMT+08:00
|
Conversion Character |
Description |
Example |
|---|---|---|
|
%tc |
Includes full date and time information |
Saturday October 27 14:21:20 CST 2007 |
|
%tF |
"year-month-day" format |
2007-10-27 |
|
%tD |
"month/day/year" format |
10/27/07 |
|
%tr |
"HH:MM:SS PM" format (12-hour clock) |
02:25:51 PM |
|
%tT |
"HH:MM:SS" format (24-hour clock) |
14:28:16 |
|
%tR |
"HH:MM" format (24-hour clock) |
14:28 |
MoreprintfFor more parsing examples, see:Java printf examples for formatted output
Example
Example
public class DateFormatExample {
public static void main(String[] args) {
Date date = new Date();
System.out.printf("%tY-%tm-%td %tH:%tM:%tS %tZ", date, date, date, date, date, date, date);
}
}
The execution output is:
2023-02-24 13:34:45 GMT+08:00
Example
The result of compiling and running the above example is as follows:
全部日期和时间信息:星期一 九月 10 10:43:36 CST 2012 年-月-日格式:2012-09-10 月/日/年格式:09/10/12 HH:MM:SS PM格式(12时制):10:43:36 上午 HH:MM:SS格式(24时制):10:43:36 HH:MM格式(24时制):10:43
If you need to provide the date repeatedly, formatting each part in this way is somewhat complicated. Therefore, you can use a format string to indicate the index of the argument to be formatted.
The index must immediately follow%% and must end with$$. For example:
Example
Run example »
The result of compiling and running the above example is as follows:
Due date: February 09, 2014
Alternatively, you can use the < flag. It indicates that the previously formatted argument is to be used again. For example:
Example
Run example »
The result of compiling and running the above example is as follows:
Due date: February 09, 2014
The conversion characters that define date formats can use the specified conversion character to generate a new string from a date. These date conversion characters are shown below:
Example
The output is:
英文月份简称:May 本地月份简称:五月 英文月份全称:May 本地月份全称:五月 英文星期的简称:Thu 本地星期的简称:星期四 年的前两位数字(不足两位前面补0):20 年的后两位数字(不足两位前面补0):17 一年中的天数(即年的第几天):124 两位数字的月份(不足两位前面补0):05 两位数字的日(不足两位前面补0):04 月份的日(前面不补0):4
Parsing Strings to Time
The SimpleDateFormat class has some additional methods, especially parse(), which attempts to parse a string according to the format stored in the given SimpleDateFormat object. For example:
Example
Run example »
The result of compiling and running the above example is as follows:
$ java DateDemo 1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818 $ java DateDemo 2007-12-01 2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007
Java Sleep
sleep() puts the current thread into a suspended state (blocks the current thread), yielding the CPU. The purpose is to prevent the current thread from monopolizing the CPU resources acquired by the process, leaving some time for other threads to execute.
You can make the program sleep for one millisecond or for any period up to the life of your computer. For example, the following program will sleep for 3 seconds:
Example
Run example »
The result of compiling and running the above example is as follows:
Thu Sep 17 10:20:30 CST 2015 Thu Sep 17 10:20:33 CST 2015
Measuring Time
The following example shows how to measure a time interval (in milliseconds):
Example
Run example »
The result of compiling and running the above example is as follows:
Fri Jan 08 09:48:47 CST 2016 Fri Jan 08 09:48:50 CST 2016 Difference is : 3019
Calendar Class
We are now able to format and create a date object, but how can we set and get specific parts of date data, such as hour, day, or minute? And how can we add or subtract values from these parts of the date? The answer is to use the Calendar class.
The Calendar class is much more powerful than the Date class, and its implementation is also more complex than the Date class.
The Calendar class is an abstract class. In practice, it implements objects of specific subclasses. The process of creating an object is transparent to programmers; you just need to use the getInstance method to create it.
Create a Calendar object representing the current date of the system
Calendar c = Calendar.getInstance();//默认是当前日期
Create a Calendar object for a specified date
To use the Calendar class to represent a specific time, you need to first create a Calendar object, then set the year, month, and day parameters of that object.
//创建一个代表2009年6月12日的Calendar对象 Calendar c1 = Calendar.getInstance(); c1.set(2009, 6 - 1, 12);
Field types of Calendar class objects
In the Calendar class, the following constants are used to represent different meanings. In fact, many classes in the JDK adopt this idea.
| Constant | Description |
|---|---|
| Calendar.YEAR | Year |
| Calendar.MONTH | Month |
| Calendar.DATE | Date |
| Calendar.DAY_OF_MONTH | Date, exactly the same meaning as the field above. |
| Calendar.HOUR | Hour in 12-hour format |
| Calendar.HOUR_OF_DAY | Hour in 24-hour format |
| Calendar.MINUTE | Minute |
| Calendar.SECOND | second |
| Calendar.DAY_OF_WEEK | Day of the week |
Setting Calendar class object information
Set setting
E.g.:
Calendar c1 = Calendar.getInstance();
Call:
public final void set(int year,int month,int date)
c1.set(2009, 6, 12);//把Calendar对象c1的年月日分别设这为:2009、6、12
Set using field types
If you only set a certain field, such as the date value, you can use the following set method:
public void set(int field,int value)
Set the date represented by the c1 object to the 10th; all other values will be recalculated.
c1.set(Calendar.DATE,10);
Set the year represented by the c1 object to 2008; all other values will be recalculated.
c1.set(Calendar.YEAR,2008);
The meaning of set for other field attributes follows the same pattern.
Add setting
Calendar c1 = Calendar.getInstance();
Add 10 to the date of the c1 object, meaning c1 represents the date 10 days later; all other values will be recalculated.
c1.add(Calendar.DATE, 10);
Subtract 10 from the date of the c1 object, meaning c1 represents the date 10 days earlier; all other values will be recalculated.
c1.add(Calendar.DATE, -10);
The meaning of add for other field attributes follows the same pattern.
Getting Calendar class object information
GregorianCalendar Class
The Calendar class implements the Gregorian calendar; GregorianCalendar is a concrete implementation of the Calendar class.
Calendar's getInstance() method returns a GregorianCalendar object initialized with the current locale and time zone by default. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.
The following lists several constructors of GregorianCalendar objects:
| No. | Constructor and description |
| 1 |
GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. |
| 2 |
GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with the given date setting in the default time zone with the default locale. |
| 3 |
GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time setting for the default time zone with the default locale. |
| 4 |
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Constructs a GregorianCalendar with the given date and time setting for the default time zone with the default locale. |
| 5 |
GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale. |
| 6 |
GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default locale. |
| 7 |
GregorianCalendar(TimeZone zone, Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale. |
Here is a list of some useful methods provided by the GregorianCalendar class:
| No. | Method and description |
| 1 |
void add(int field, int amount) Adds the specified (signed) amount of time to the given calendar field according to the calendar rules. |
| 2 |
protected void computeFields() Converts UTC millisecond value to time field values. |
| 3 |
protected void computeTime() Overrides Calendar, converting time field values to UTC millisecond value. |
| 4 |
boolean equals(Object obj) Compares this GregorianCalendar with the specified Object. |
| 5 |
int get(int field) Gets the time value for the specified field. |
| 6 |
int getActualMaximum(int field) Returns the maximum value of the given field for the current date. |
| 7 |
int getActualMinimum(int field) Returns the minimum value of the given field for the current date. |
| 8 |
int getGreatestMinimum(int field) Returns the highest minimum value of the given calendar field for this GregorianCalendar instance. |
| 9 |
Date getGregorianChange() Gets the Gregorian calendar change date. |
| 10 |
int getLeastMaximum(int field) Returns the lowest maximum value of the given calendar field for this GregorianCalendar instance. |
| 11 |
int getMaximum(int field) Returns the maximum value of the given calendar field for this GregorianCalendar instance. |
| 12 |
Date getTime() Gets the current time of the calendar. |
| 13 |
long getTimeInMillis() Gets the current time of the calendar represented as a long. |
| 14 |
TimeZone getTimeZone() Gets the time zone. |
| 15 |
int getMinimum(int field) Returns the minimum value of the given field. |
| 16 |
int hashCode() Overrides hashCode. |
| 17 |
boolean isLeapYear(int year) Determines whether the given year is a leap year. |
| 18 |
void roll(int field, boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. |
| 19 |
void set(int field, int value) Sets the time field with the given value. |
| 20 |
void set(int year, int month, int date) Sets the values of year, month, and day. |
| 21 |
void set(int year, int month, int date, int hour, int minute) Sets the values of year, month, day, hour, and minute. |
| 22 |
void set(int year, int month, int date, int hour, int minute, int second) Sets the values of year, month, day, hour, minute, and second. |
| 23 |
void setGregorianChange(Date date) Sets the change date of the GregorianCalendar. |
| 24 |
void setTime(Date date) Sets the Calendar's current time with the given date. |
| 25 |
void setTimeInMillis(long millis) Sets the Calendar's current time with the given long millisecond value. |
| 26 |
void setTimeZone(TimeZone value) Sets the current time zone with the given time zone value. |
| 27 |
String toString() Returns a string representing the calendar. |
Example
Example
Run example »
The result of compiling and running the above example is as follows:
Date: Apr 22 2009 Time: 11:25:27 当前年份不是闰年
For a complete list of the Calendar class, you can refer to the standardJava documentation。
Other extensions