Easy Tutorial
❮ File Delete Collection Sublist ❯

Java Date and Time

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 takes a parameter, which is the number of milliseconds since January 1, 1970.

Date(long millisec)

After creating a Date object, you can call the following methods.

No. Method and Description
1 boolean after(Date date) <br>Returns true if the invoking Date object contains a date that is later than the specified date, otherwise returns false.
2 boolean before(Date date) <br>Returns true if the invoking Date object contains a date that is earlier than the specified date, otherwise returns false.
3 Object clone() <br>Returns a copy of this object.
4 int compareTo(Date date) <br>Compares the value of the invoking Date object with the specified date. Returns 0 if they are equal. Returns a negative number if the invoking object is earlier than the specified date. Returns a positive number if the invoking object is later than the specified date.
5 int compareTo(Object obj) <br>If obj is of type Date, the operation is the same as compareTo(Date). Otherwise, it throws a ClassCastException.
6 boolean equals(Object date) <br>Returns true if the invoking Date object and the specified date are equal, otherwise returns false.
7 long getTime() <br>Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
8 int hashCode() <br>Returns the hash code value for this object.
9 void setTime(long time) <br>Sets the time and date as specified by time, which is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
10 String toString() <br>Converts the Date object to a string in the form: dow mon dd hh:mm:ss zzz yyyy, where dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).

Getting the Current Date and Time

Getting the current date and time in Java is straightforward. Use 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();

       // Display date and time using toString()
       System.out.println(date.toString());
   }
}

The above example compiles and runs with the following result:

Mon May 04 09:51:52 CDT 2013

Date Comparison

Java uses the following three methods to compare two dates:


Formatting Dates Using SimpleDateFormat

SimpleDateFormat is a class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. 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("Current Date: " + ft.format(dNow));
   }
}

The above example compiles and runs with the following result:

Current Date: 2013-05-04 09:51:52
System.out.println("Current time is: " + ft.format(dNow));
}
}
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

This line of code establishes the format for conversion, where yyyy is the full year, MM is the month, dd is the day of the month, and HH:mm:ss is the hour, minute, and second.

Note: Some formats are uppercase and some are lowercase; for example, MM is for months and mm is for minutes; HH is for a 24-hour format, while hh is for a 12-hour format.

The above example compiles and runs with the following result:

Current time is: 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 designator AD
y Year in four digits 2001
M Month in year July or 07
d Day in month 10
h Hour in A.M./P.M. (1~12) 12
H Hour in day (0~23) 22
m Minute in hour 30
s Second in minute 55
S Millisecond 234
E Day in week Tuesday
D Day in 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 in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
' Escape for text Delimiter
" Single quote `

Formatting Dates with printf

The printf method can easily format dates and times. Using a two-letter format, it starts with %t and ends with one of the letters from the table below.

Conversion符 Description Example
c Full date and time Monday October 27 14:21:20 CST 2007
F "Year-Month-Day" format 2007-10-27
D "Month/Day/Year" format 10/27/07
r "HH:MM:SS PM" format (12-hour clock) 02:25:51 PM
T "HH:MM:SS" format (24-hour clock) 14:28:16
R "HH:MM" format (24-hour clock) 14:28

For more printf parsing, see: Java Formatting Output printf Example

Example

import java.util.Date;

public class DateDemo {

  public static void main(String[] args) {
     // Initialize Date object
     Date date = new Date();

     // Usage of c
    System.out.printf("Full date and time: %tc%n", date);          
    // Usage of F
    System.out.printf("Year-Month-Day format: %tF%n", date);  
    // Usage of D
    System.out.printf("Month/Day/Year format: %tD%n", date);  
    // Usage of r
    System.out.printf("HH:MM:SS PM format (12-hour clock): %tr%n", date);  
    // Usage of t
    System.out.printf("HH:MM:SS format (24-hour clock): %tT%n", date);  
    // Usage of R
    System.out.printf("HH:MM format (24-hour clock): %tR", date);  
  }
}

The above example compiles and runs with the following result:

Full date and time: Monday September 10 10:43:36 CST 2012  
Year-Month-Day format: 2012-09-10  
Month/Day/Year format: 09/10/12  
HH:MM:SS PM format (12-hour clock): 10:43:36 AM  
HH:MM:SS format (24-hour clock): 10:43:36  
HH:MM format (24-hour clock): 10:43

HH:MM:SS format (24-hour clock): 10:43:36 HH:MM format (24-hour clock): 10:43

If you need to repeatedly provide dates, formatting each part of it in this way can be a bit cumbersome. Therefore, you can use a format string to indicate the index of the parameter to be formatted.

The index must follow immediately after the % 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();

       // Display date and time using toString()
       System.out.printf("%1$s %2$tB %2$td, %2$tY", 
                         "Due date:", date);
   }
}

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 parameter should 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 %&lt;te, %&lt;tY", 
                         "Due date:", date);
   }
}

The result of compiling and running the above example is as follows:

Due date: February 09, 2014

Defining date format conversion specifiers allows dates to be generated into new strings through specified conversion specifiers. These date conversion specifiers are as follows:

Example

import java.util.*;

public class DateDemo {
   public static void main(String[] args) {
       Date date = new Date();                                      
        // Usage of 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);  
        // Usage of 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);  
        // Usage of a, weekday abbreviation  
        str = String.format(Locale.US, "English weekday abbreviation: %ta", date);  
        System.out.println(str);  
        // Usage of A, full weekday name  
        System.out.printf("Local weekday abbreviation: %tA%n", date);  
        // Usage of C, first two digits of the year  
        System.out.printf("First two digits of the year (padded with 0 if necessary): %tC%n", date);  
        // Usage of y, last two digits of the year  
        System.out.printf("Last two digits of the year (padded with 0 if necessary): %ty%n", date);  
        // Usage of j, day of the year  
        System.out.printf("Day of the year: %tj%n", date);  
        // Usage of m, month in two digits  
        System.out.printf("Two-digit month (padded with 0 if necessary): %tm%n", date);  
        // Usage of d, day of the month in two digits  

Two-digit day (padded with 0 if less than two digits): %td%n // Usage of 'e', day (not padded with 0 if one digit) Day of the month (not padded with 0): %te } }

Output result:

English month abbreviation: May
Local month abbreviation: May
English month full name: May
Local month full name: May
English weekday abbreviation: Thu
Local weekday abbreviation: Thursday
First two digits of the year (padded with 0 if less than two digits): 20
Last two digits of the year (padded with 0 if less than two digits): 17
Day of the year (i.e., the nth day of the year): 124
Two-digit month (padded with 0 if less than two digits): 05
Two-digit day (padded with 0 if less than two digits): 04
Day of the month (not padded with 0): 4

Parsing String to Date

The SimpleDateFormat class has additional methods, particularly parse(), which attempts to parse a string according to the formatting stored by 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);
      }
   }
}

Compilation and running result of the above example:

$ 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() causes the current thread to enter a blocked state, relinquishing the use of the CPU. The purpose is to prevent the current thread from monopolizing the CPU resources of the process, allowing other threads to execute for a certain period of time.

You can make the program sleep for a millisecond or for as long as the lifespan 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!");
      }
   }
}

Compilation and running result of the above example:

Thu Sep 17 10:20:30 CST 2015

Thu Sep 17 10:20:33 CST 2015

Measuring Time

The following example demonstrates how to measure the 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");
```java
long end = System.currentTimeMillis();
long diff = end - start;
System.out.println("Difference is : " + diff);
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}

The above example compiles and runs with the following results:

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 the date, such as hours, days, or minutes? 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 is also more complex in its implementation.

The Calendar class is an abstract class, and in practical use, it implements specific subclass objects. The process of creating objects is transparent to the programmer, and you only need to use the getInstance method to create one.

Creating a Calendar object representing the current system date

Calendar c = Calendar.getInstance(); // default is the current date

Creating a Calendar object for a specified date

To represent a specific time using the Calendar class, you first need to create a Calendar object and then set the year, month, and day parameters of that object.

// Create a Calendar object representing June 12, 2009
Calendar c1 = Calendar.getInstance();
c1.set(2009, 6 - 1, 12);

Calendar class field types

The Calendar class uses the following constants to represent different meanings. Many classes in the JDK use this idea.

Constant Description
Calendar.YEAR Year
Calendar.MONTH Month
Calendar.DATE Date
Calendar.DAY_OF_MONTH Date, same meaning as above
Calendar.HOUR 12-hour format hour
Calendar.HOUR_OF_DAY 24-hour format hour
Calendar.MINUTE Minute
Calendar.SECOND Second
Calendar.DAY_OF_WEEK Day of the week

Setting information in Calendar objects

Set Method

Example:

Calendar c1 = Calendar.getInstance();

Call:

public final void set(int year, int month, int date)
c1.set(2009, 6, 12); // Set the year, month, and day of the Calendar object c1 to 2009, 6, and 12 respectively

Setting using field types

If you only want to set a specific 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, and all other values will be recalculated.

c1.set(Calendar.DATE, 10);

Set the year represented by the c1 object to 2008, and all other values will be recalculated.

c1.set(Calendar.YEAR, 2008);

The meaning of other field properties set is analogous.

Add Method

Calendar c1 = Calendar.getInstance();

Add 10 to the date of the c1 object, which means c1 represents the date 10 days later, and all other values will be recalculated.

c1.add(Calendar.DATE, 10);

Subtract 10 from the date of the c1 object, which means c1 represents the date 10 days earlier, and all other values will be recalculated.

c1.add(Calendar.DATE, -10);

The meaning of other field properties add is analogous.

Getting information from Calendar objects

Calendar c1 = Calendar.getInstance();
// Get the year
int year = c1.get(Calendar.YEAR);
// Get the month
int month = c1.get(Calendar.MONTH) + 1;
// Get the date
int date = c1.get(Calendar.DATE);
// Get the 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 the week (Note: 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, and GregorianCalendar is a concrete implementation of the Calendar class.

The getInstance() method of Calendar returns a GregorianCalendar object initialized with the current locale and time zone. GregorianCalendar defines two fields: AD and BC, which represent the two eras defined by the Gregorian calendar.

Below are several constructors of the GregorianCalendar object:

No. Constructor and Description
1 GregorianCalendar() <br>Constructs a default GregorianCalendar using the current time in the default locale and time zone.
2 GregorianCalendar(int year, int month, int date) <br>Constructs a GregorianCalendar with the given date set in the default locale and time zone.
3 GregorianCalendar(int year, int month, int date, int hour, int minute) <br>Constructs a GregorianCalendar with the given date and time set in the default locale and time zone.
4 GregorianCalendar(int year, int month, int date, int hour, int minute, int second) <br>Constructs a GregorianCalendar with the given date and time set in the default locale and time zone.
5 GregorianCalendar(Locale aLocale) <br>Constructs a GregorianCalendar based on the current time in the given locale and default time zone.
6 GregorianCalendar(TimeZone zone) <br>Constructs a GregorianCalendar based on the current time in the default locale and given time zone.
7 GregorianCalendar(TimeZone zone, Locale aLocale) <br>Constructs a GregorianCalendar based on the current time in the given locale and time zone.

Here is a list of some useful methods provided by the GregorianCalendar class:

No. Method and Description
1 void add(int field, int amount) <br>Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.
2 protected void computeFields() <br>Converts UTC milliseconds to time field values.
3 protected void computeTime() <br>Overrides Calendar, converts time field values to UTC milliseconds.
4 boolean equals(Object obj) <br>Compares this GregorianCalendar to the specified Object.
5 int get(int field) <br>Gets the time value of the specified field.
6 int getActualMaximum(int field) <br>Returns the maximum value of the given field for the current date.
7 int getActualMinimum(int field) <br>Returns the minimum value of the given field for the current date.
8 int getGreatestMinimum(int field) <br>Returns the highest minimum value of the given calendar field for this GregorianCalendar instance.
9 Date getGregorianChange() <br>Gets the Gregorian change date.
10 int getLeastMaximum(int field) <br>Returns the lowest maximum value of the given calendar field for this GregorianCalendar instance.
11 int getMaximum(int field) <br>Returns the maximum value of the given calendar field for this GregorianCalendar instance.
12 Date getTime() <br>Get the current time of the calendar.
13 long getTimeInMillis() <br>Get the current time of the calendar as a long integer.
14 TimeZone getTimeZone() <br>Get the time zone.
15 int getMinimum(int field) <br>Return the minimum value for the given field.
16 int hashCode() <br>Override hashCode.
17 boolean isLeapYear(int year) <br>Determine if the given year is a leap year.
18 void roll(int field, boolean up) <br>Add or subtract (up/down) a single time unit in the given time field without changing larger fields.
19 void set(int field, int value) <br>Set the time field with the given value.
20 void set(int year, int month, int date) <br>Set the values for year, month, and date.
21 void set(int year, int month, int date, int hour, int minute) <br>Set the values for year, month, date, hour, and minute.
22 void set(int year, int month, int date, int hour, int minute, int second) <br>Set the values for year, month, date, hour, minute, and second.
23 void setGregorianChange(Date date) <br>Set the change date for GregorianCalendar.
24 void setTime(Date date) <br>Set the current time of the Calendar with the given date.
25 void setTimeInMillis(long millis) <br>Set the current time of the Calendar with the given long integer milliseconds.
26 void setTimeZone(TimeZone value) <br>Set the current time zone with the given time zone value.
27 String toString() <br>Return a string representing the calendar.

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
      // Using the 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 if 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");

The compilation and execution results of the above example are as follows:

Date: Apr 22 2009
Time: 11:25:27
The current year is not a leap year

For a complete list of the Calendar class, you can refer to the standard Java documentation. ```

❮ File Delete Collection Sublist ❯