Java date 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 using the current date and time.

Date( )

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

Date(long millisec)

After the Date object is created, you can call the following method.

              Serial number             Method and description
            1boolean after(Date date)
If the Date object that calls this method is after the specified date, it returns true, otherwise it returns false.
              2boolean before(Date date)
If the Date object calling this method returns true before the specified date, otherwise it returns false.
              3Object clone( )
Returns a copy of this object.
              4int compareTo(Date date)
Compares the Date object and the specified date when this method is called. When the two are equal, 0 is returned. If the calling object is before the specified date, a negative number is returned. The calling object returns a positive number after the specified date.
              5int compareTo(Object obj)
If obj is of Date type, the operation is equivalent to compareTo(Date). Otherwise it throws ClassCastException.
              6boolean equals(Object date)
Returns true when the Date object calling this method is equal to the specified date, otherwise it returns false.
              7long getTime( )
Returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT.
              8int hashCode( )
Returns the hash code value of this object.
              9void setTime(long time)

Set the time and date in milliseconds since January 1, 1970 00:00:00 GMT.
              10String toString( )
Converts a Date object to a String representation and returns the string.

Getting the current date and time

Getting the current date and time in Java is very simple. Use the toString() method of the Date object to print the current date and time, as shown below:

import java.util.Date;
  
public class DateDemo {
   public static void main(String args[]) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 使用 toString() 函数显示日期时间
       System.out.println(date.toString());
   }
}

The above example compilation and running results are 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 get two dates (the number of milliseconds since January 1, 1970), and then compare the two values.

  •             Use the methods before(), after() and equals(). For example, if the 12th of a month is earlier than the 18th, then new 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.


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 and time format to run on. For example:

import java.util.*;
import java.text.*;

public class DateDemo {
   public static void main(String args[]) {

      Date dNow = new Date( );
      SimpleDateFormat ft = 
      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

      System.out.println("Current Date: " + ft.format(dNow));
   }
}

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

Current Date: Sun 2004.07.18 at 04:14:09 PM PDT

Simple DateFormat formatting encoding

The time pattern string is used to specify the time format. In this mode, all ASCII letters are reserved as pattern letters, defined as follows:

##               y             Four-digit year             2001             M             Month             July or 07             d             The date of the month           10             h               A.M./P.M. (1~12) format hour               12             H             Hour of the day (0~23)             twenty two m               Number of minutes           30             s             Seconds             55##               w             Week of the year             40             W             Week of the month           1 a             A.M./P.M. Mark           PM             k             Hour of the day (1~24)               twenty four##               '             Text delimiter               Delimiter             "             apostrophe `

Use printf to format dates

The printf method can easily format time and date. Use the two-letter format, which begins with t and ends with a letter from the table below. For example:

import java.util.Date;

public class DateDemo {

  public static void main(String args[]) {
     // 初始化 Date 对象
     Date date = new Date();

     // 使用toString()显示日期和时间
     String str = String.format("Current Date/Time : %tc", date );

     System.out.printf(str);
  }
}

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

Current Date/Time : Sat Dec 15 16:37:57 MST 2012

If you need to repeatedly provide the date, use this method to format it Every part of it is a little more complicated. Therefore, a format string can be used to indicate the index of the parameter to be formatted.

The index must immediately follow % and must end with $. For example:

import java.util.Date;
  
public class DateDemo {

   public static void main(String args[]) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 使用toString()显示日期和时间
       System.out.printf("%1$s %2$tB %2$td, %2$tY", 
                         "Due date:", date);
   }
}

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

Due date: February 09, 2004

Alternatively, you can use the < sign. It indicates that previously formatted parameters are to be used again. For example:

import java.util.Date;
  
public class DateDemo {

   public static void main(String args[]) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 显示格式化时间
       System.out.printf("%s %tB %<te, %<tY", 
                         "Due date:", date);
   }
}

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

Due date: February 09, 2004

Date and time conversion characters

LettersDescriptionExample
              G               Epoch mark             AD
              S             Number of milliseconds               234
            E             Day of the week Tuesday
              D             Days of the year             360
            F             Day of the week             2 (second Wed. in July)
              K             A.M./P.M. (0~11) format hour                 10
            z Time zone Eastern Standard Time
##             D             U.S. format date (month/day/year)             02/09/2004##               T             r##             R             24 hours, excluding seconds             18:05             Y             4-digit year (including leading 0)               2004             y             Last 2 digits of year (including leading 0)               04##               n             2-digit month (including leading 0)               02               d             2-digit date (including leading 0)             03             e             2-digit date (excluding leading 0)             9 A             Full name of the week             Monday             a             Abbreviation of week             Mon##             P             Uppercase afternoon sign             PM             p               Lower case uppercase afternoon sign             pm               z RFC 822 digital offset from GMT             -0800             Z Time zone PST             s             Number of seconds since 1970-01-01 00:00:00 GMT             1078884319##               Q

There are other useful date and time related classes. For more details, you can refer to the Java standards documentation.


Parsing a string as a time

The SimpleDateFormat class has some additional methods, especially parse(), which attempts to parse the string according to the formatted storage of the given SimpleDateFormat object . For 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); 
      }
   }
}

The above example compilation and running results are 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)

sleep() causes the current thread to enter a stagnant state (blocking the current thread ), the purpose of giving up the use of the CPU is to prevent the current thread from occupying the CPU resources obtained by the process alone, so as to leave a certain amount of time for other threads to execute.

You can put a program to sleep for a millisecond or as long as your computer lasts. For example, the following program will sleep for 3 seconds:

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

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

Thu Sep 17 10:20:30 CST 2015

Thu Sep 17 10:20:33 CST 2015

Measurement time

The following example shows how to measure the time interval (in milliseconds):

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!");
      }
   }
}

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

Fri Jan 08 09:48:47 CST 2016

Fri Jan 08 09:48:50 CST 2016

Difference is : 3019

Calendar Class

We can now format and create a date object, but how can we set and get specific parts of the date data, such as the hour, day, or minute? How do 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 that implements objects of specific subclasses in actual use. The process of creating objects is transparent to programmers, and only needs to be created using the getInstance method.

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 , and then set the year, month and day parameters in the object to complete.

//创建一个代表2009年6月12日的Calendar对象
Calendar c1 = Calendar.getInstance();
c1.set(2009, 6 - 1, 12);

Calendar class object field type

These constants are used in the Calendar class to represent different meanings. Many classes in jdk actually adopt this idea

CharactersDescription example
              c               Complete date and time             Mon May 04 09:51:52 CDT 2009
              F             ISO 8601 format date             2004-02-09
            24 hours time             18:05:19
            12 hours             06:05:19 pm
              C             The first 2 digits of the year (including leading 0)               20
            B             Full name of month             February
              b             Month abbreviation             Feb
              j               3-digit year (including leading 0)               069
            H             2-digit hour (including leading 0), 00 to 23               18
              k               2-digit hour (excluding leading 0), 0 to 23               18
              I             2-digit hour (including leading 0), 01 to 12               06
              l             2-digit hour (excluding leading 0), 1 to 12                 6
            M             2-digit minute (including leading 0)               05
              S             2-digit seconds (including leading 0)               19
            L             3-digit milliseconds (including leading 0)               047
              N             9-digit nanosecond (including leading 0)               047000000
            Since 1970-01-01 00:00:00 GMT's subtlety             1078884319047
##Calendar.DAY_OF_WEEKDay of the week

Calendar class object information setting

Set setting

For example:

Calendar c1 = Calendar.getInstance();

Call:

public final void set(int year,int month,int date)
c1.set(2009, 6 - 1, 12);//把Calendar对象c1的年月日分别设这为:2009、6、12

Use field type Setting

If you only set a certain field, such as the value of date, 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 Being 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 attribute sets is deduced in the same way

Add setting

Calendar c1 = Calendar.getInstance();

Add 10 to the date of the c1 object, that is, c1 is expressed as 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, that is, c1 is expressed as the date 10 days ago, and all other values ​​​​will be recalculated

<pre>c1.add(Calendar.DATE, -10);

The meaning of add for other field attributes is deduced in this way

Acquisition of Calendar class object information

Calendar c1 = Calendar.getInstance();
// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;
// 获得日期
int date = c1.get(Calendar.DATE);
// 获得小时
int hour = c1.get(Calendar.HOUR_OF_DAY);
// 获得分钟
int minute = c1.get(Calendar.MINUTE);
// 获得秒
int second = c1.get(Calendar.SECOND);
// 获得星期几(注意(这个与Date类是不同的):1代表星期日、2代表星期1、3代表星期二,以此类推)
int day = c1.get(Calendar.DAY_OF_WEEK);

GregorianCalendar class

The Calendar class implements the Gregorian calendar, and GregorianCalendar is a specific implementation of the Calendar class.

Calendar’s getInstance() method returns a GregorianCalendar object initialized by default with the current locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

Listed below are several construction methods of the GregorianCalendar object:

ConstantDescription
Calendar.YEARYear
Calendar.MONTHmonth
Calendar.DATE
Calendar.DAY_OF_MONTH Date has the same meaning as the above field
Calendar.HOURHour in 12-hour format
Calendar.HOUR_OF_DAYHour in 24-hour format
Calendar.MINUTEMinute
Calendar. SECONDSeconds
##             1               2               3               4               5               6               7

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

Serial numberConstructor and description
GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with the given date settings in the default time zone with the default locale
GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time settings for the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Constructs a GregorianCalendar with the given date and time settings for the default time zone with the default locale.
GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
GregorianCalendar(TimeZone zone, Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.
##             1               2               3             4               5             6               7               8               9               10             11
Serial numberMethod and instructions
void add(int field, int amount) Adds the specified (signed) amount of time to the given calendar field according to calendar rules.
protected void computeFields() Convert UTC millisecond value to time domain value
protected void computeTime() Override Calendar and convert the time domain value to UTC millisecond value
boolean equals(Object obj) Compares this GregorianCalendar to the specified Object.
int get(int field) Get the time value of the specified field
int getActualMaximum(int field) Returns the current date, the maximum value of the given field
int getActualMinimum(int field) Returns the current date, the minimum value of the given field
int getGreatestMinimum(int field) Returns the highest minimum value for the given calendar field in this GregorianCalendar instance.
Date getGregorianChange() Get the Gregorian calendar change date.
int getLeastMaximum(int field) Returns the lowest maximum value for the given calendar field of this GregorianCalendar instance
int getMaximum(int field) Returns the maximum value of the given calendar field for this GregorianCalendar instance.
              12Date getTime()
Get the current time of the calendar.
              13long getTimeInMillis()
Get the current time of the calendar represented by a long integer
            14TimeZone getTimeZone()
Get the time zone.
              15int getMinimum(int field)
Returns the minimum value of the given field.
          &