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.LocalDate;
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
  1. New projects should prefer the java.time package (Java 8+)

  2. Avoid using the legacy Date and Calendar classes

  3. Clearly distinguish time zone usage:

    • No time zone needed: LocalDate/LocalTime/LocalDateTime

    • Time zone needed: ZonedDateTime

  4. Consider thread safety when formatting: Use DateTimeFormatter instead of SimpleDateFormat

  5. Database interaction:

    • JDBC 4.2+ natively supports java.time types

    • Older versions can convert to java.sql.Date/Timestamp

1. LocalDate (Date)

Example

LocalDate today = LocalDate.now();
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 now = LocalTime.now();
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 ldt = LocalDateTime.now();
LocalDateTime dt = LocalDateTime.of(2023, 6, 15, 14, 30);
LocalDateTime nextMonth = dt.plusMonths(1);

4. ZonedDateTime (Date and Time with Time Zone)

Example

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime nyTime = zdt.withZoneSameInstant(ZoneId.of("America/New_York"));
ZoneId zone = zdt.getZone();  // Get time zone

5. Instant (Timestamp)

Example

Instant now = Instant.now();  // Get current timestamp
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.

Date( )

The second constructor accepts a parameter, which is the number of milliseconds since January 1, 1970.

Date(long millisec)

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

import java.util.Date; public class DateDemo { public static void main(String[] args) { //Initialize Date object Date date = new Date(); //Use toString() function to display date and time System.out.println(date.toString()); } }

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

import java.util.Date;

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

import java.util.Date;

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

import java.util.Date;

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

import java.util.*; import java.text.*; public class DateDemo { public static void main(String[] args) { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); System.out.println("The current time is:" + ft.format(dNow)); } }

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

import java.util.Date;
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

import java.util.Date; public class DateDemo { public static void main(String[] args) { //Initialize Date object Date date = new Date(); //Using c System.out.printf("Full date and time information: %tc%n",date); //Using f System.out.printf("year-month-day format: %tF%n",date); //Using d System.out.printf("month/day/year format: %tD%n",date); //Using r System.out.printf("HH:MM:SS PM format (12-hour clock): %tr%n",date); //Using t System.out.printf("HH:MM:SS format (24-hour clock): %tT%n",date); //Using R System.out.printf("HH:MM format (24-hour clock): %tR",date); } }

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

import java.util.Date; public class DateDemo { public static void main(String[] args) { //Initialize Date object Date date = new Date(); //Using toString() to Display Date and Time System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); } }

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

import java.util.Date; public class DateDemo { public static void main(String[] args) { //Initialize Date object Date date = new Date(); //Display formatted time System.out.printf("%s %tB %<te, %<tY", "Due date:", date); } }

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

import java.util.*; public class DateDemo { public static void main(String[] args) { Date date=new Date(); //Using b, month abbreviation String str=String.format(Locale.US,"English month abbreviation: %tb",date); System.out.println(str); System.out.printf("Local month abbreviation: %tb%n",date); //Using B, full month name str=String.format(Locale.US,"English full month name: %tB",date); System.out.println(str); System.out.printf("Local full month name: %tB%n",date); //Using a, weekday abbreviation str=String.format(Locale.US,"English weekday abbreviation: %ta",date); System.out.println(str); //Using A, full weekday name System.out.printf("Local weekday abbreviation: %tA%n",date); //Using C, first two digits of year System.out.printf("The first two digits of the year (zero-padded if less than two digits): %tC%n",date); //Using y, last two digits of year System.out.printf("The last two digits of the year (zero-padded if less than two digits): %ty%n",date); //Using j, day of the year System.out.printf("The day of the year (i.e., the nth day of the year): %tj%n",date); //Using m, month System.out.printf("Two-digit month (zero-padded if less than two digits): %tm%n",date); //Using d, day (two digits, zero-padded if needed) System.out.printf("Two-digit day (zero-padded if less than two digits): %td%n",date); //Using e, day (single digit without zero padding) System.out.printf("Day of the month (no leading zero): %te",date); } }

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

import java.util.*; import java.text.*; public class DateDemo { public static void main(String[] args) { SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); String input = args.length == 0 ? "1818-11-11" : args[0]; System.out.print(input + " Parses as "); Date t; try { t = ft.parse(input); System.out.println(t); } catch (ParseException e) { System.out.println("Unparseable using " + ft); } } }

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

import java.util.*; public class SleepDemo { public static void main(String[] args) { try { System.out.println(new Date( ) + "\n"); Thread.sleep(1000*3); //Sleep for 3 seconds System.out.println(new Date( ) + "\n"); } catch (Exception e) { System.out.println("Got an exception!"); } } }

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

import java.util.*; public class DiffDemo { public static void main(String[] args) { try { long start = System.currentTimeMillis( ); System.out.println(new Date( ) + "\n"); Thread.sleep(5*60*10); System.out.println(new Date( ) + "\n"); long end = System.currentTimeMillis( ); long diff = end - start; System.out.println("Difference is : " + diff); } catch (Exception e) { System.out.println("Got an exception!"); } } }

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.

ConstantDescription
Calendar.YEARYear
Calendar.MONTHMonth
Calendar.DATEDate
Calendar.DAY_OF_MONTHDate, exactly the same meaning as the field above.
Calendar.HOURHour in 12-hour format
Calendar.HOUR_OF_DAYHour in 24-hour format
Calendar.MINUTEMinute
Calendar.SECONDsecond
Calendar.DAY_OF_WEEKDay 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

Calendar c1 = Calendar.getInstance(); //Get year int year = c1.get(Calendar.YEAR); //Get month int month = c1.get(Calendar.MONTH) + 1; //Get date int date = c1.get(Calendar.DATE); //Get hour int hour = c1.get(Calendar.HOUR_OF_DAY); //Get minute int minute = c1.get(Calendar.MINUTE); //Get second int second = c1.get(Calendar.SECOND); //Get day of week (note this is different from the Date class: 1 represents Sunday, 2 represents Monday, 3 represents Tuesday, and so on) int day = c1.get(Calendar.DAY_OF_WEEK);

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

import java.util.*; public class GregorianCalendarDemo { public static void main(String[] args) { String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int year; //Initialize Gregorian calendar //Use current time and date //Defaults to local time and time zone GregorianCalendar gcalendar = new GregorianCalendar(); //Display current time and date information System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND)); //Test whether the current year is a leap year if(gcalendar.isLeapYear(year)) { System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year"); } } }

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