Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java date time


May 10, 2021 Java


Table of contents


Java date time

The java.util package provides a Date class to encapsulate the current date and time. The Date class provides two constructors to instantiate the Date object.

The first constructor initializes the object using the current date and time.

Date( )

The second constructor receives an argument for microseconds from January 1, 1970.

Date(long millisec)

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

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

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

Gets the current date 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 follows:

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 examples compile and run as follows:

Mon May 04 09:51:52 CDT 2013

Date comparison

Java uses three methods to compare two dates:

  • Use the getTime( ) method to get two dates (microsecond values experienced since January 1, 1970) and compare the two values.
  • Use methods before(), after(), and equals(). For example, if the 12th of a month is earlier than the 18th, new Date (99, 2, 12). before (99, 2, 18)) returns true.
  • Using the makeTo() method, which is defined by the Compale interface, the Date class implements this interface.

Format the date using SimpleDateFormat

SimpleDateFormat is a class that formats and analyzes dates in a language-sensitive way. S impleDateFormat allows you to select any user-defined date-time format to run. F or 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 above examples compile and run as follows:

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

Simple DateFormat formatting coding

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

Letters Describe Example
G Era mark AD
Y Four years 2001
M Month July or 07
D The date of the month 10
H A.M./P .M. (1 to 12) format hours 12
H Hours of the day (0-23) 22
M Minutes 30
s The number of seconds 55
S Subtle numbers 234
E What day of the week Tuesday
D The day of the year 360
F The week of the first few weeks of the month 2 (second Wed. in July)
W The first few weeks of the year 40
W The first few weeks of the month 1
A A.M./P.M. Tag Pm
K Hours of the day (1 to 24) 24
K A.M./p.m. (0 ~ 11) format hours 10
Z Time Eastern Standard Time
' Text bounding Delimiter
" Single quotes `

Format the date using printf

The printf method makes it easy to format time and date. U sing the two-letter format, it begins with t and ends with a letter in 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 above examples compile and run as follows:

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

If you need to provide the date repeatedly, formatting each part of it in this way is a bit complicated. Therefore, you can use a formatted string to indicate the index of the parameters to be formatted.

The index must 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 above examples compile and run as follows:

Due date: February 09, 2004

Alternatively, you can use the .lt; logo. I t indicates that the 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 above examples compile and run as follows:

Due date: February 09, 2004

Date and time conversion characters

Character Describe Example
C Full date and time Mon May 04 09:51:52 CDT 2009
F ISO 8601 format date 2004-02-09
D U.S. Format Date (Month/Day/Year) 02/09/2004
T 24 hours 18:05:19
R 12 hours 06:05:19 pm
R 24 hours, no seconds 18:05
Y 4-bit year (including leading 0) 2004
Y 2 bits after the year (including leading 0) 04
C Top 2 bits of the year (including leading 0) 20
B Full name of the month February
B Short for month Feb
N 2-bit month (including leading 0) 02
D 2 bit days (including leading 0) 03
E 2 bit days (no leading 0 included) 9
A Full name of the week Monday
A Short for the week Mon
J 3-bit year (including leading 0) 069
H 2 bit hours (including leading 0), 00 to 23 18
K 2 bit hours (without leading 0), 0 to 23 18
2 bit hours (including leading 0), 01 to 12 06
l 2 bit hours (without leading 0), 1 to 12 6
M 2 bit minutes (including leading 0) 05
S 2 bits of seconds (including leading 0) 19
L 3 bit milliseconds (including leading 0) 047
N 9 bit nanconds (including leading 0) 047000000
P Capitals on the afternoon sign Pm
P Small on the afternoon sign Pm
Z Offset from the RFC 822 number at GMT -0800
Z Time Pst
s Seconds from 1970-01-01 00:00:00 GMT 1078884319
Q Since 1970-01-01 00:00:00 GMT 1078884319047

There are other useful date and time-related classes. F or more details, you can refer to the Java standard documentation.


The parsing string is time

The SimpleDateFormat class has some additional methods, especially parse(), which attempts to parse strings according to the formatted storage of a given SimpleDateFormat object. F or 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 examples compile and run 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 Hibernation (sleep)

You can put the program to sleep for a millisecond or for any time your computer lasts longer. For example, the following program sleeps for 3 seconds:

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

The above examples compile and run as follows:

Sun May 03 18:04:41 GMT 2009

Sun May 03 18:04:44 GMT 2009

Measure the time

The following example shows how to measure time intervals 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 above examples compile and run as follows:

Sun May 03 18:16:51 GMT 2009

Sun May 03 18:16:57 GMT 2009

Difference is : 5993

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 data, such as hours, days, or minutes? H ow do we add or subtract values from these parts of the date? T he answer is to use the Calendar class.

Calendar classes are much more powerful than Date classes and are more complex to implement than Date classes.

A Calendar class is an abstract class that implements objects of a particular sub-class when actually used, and the process of creating an object is transparent to the programmer, requiring only the getInstance method to create it.

Create a Calendar object that represents the current date of the system

Calendar c = Calendar.getInstance();//默认是当前日期

Create a Calendar object with a specified date

Using the Calendar class to represent a specific time, you need to create a Calendar object before setting the year-and-day parameters in that object to complete it.

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

Calendar class object field type

Use these constants in calendar classes to represent different meanings, and many of the classes within jdk actually use this idea

Constant Describe
Calendar.YEAR Year
Calendar.MONTH Month
Calendar.DATE Date
Calendar.DAY_OF_MONTH Date, which means exactly the same as the field above
Calendar.HOUR 12-hour hours
Calendar.HOUR_OF_DAY 24-hour hours
Calendar.MINUTE Minutes
Calendar.SECOND Seconds
Calendar.DAY_OF_WEEK What day of the week

The setting of the Calendar class object information

Set settings

Such as:

Calendar c1 = Calendar.getInstance();

Call:

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

Use field type settings

If you set only one field, such as the value of a date, you can use the set method as follows:

public void set(int field,int value)

Set the date represented by the c1 object to number 10 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 are recalculated

c1.set(Calendar.YEAR,2008);

The meaning of other field properties set and so on

Add settings

Calendar c1 = Calendar.getInstance();

Add the date of the c1 object to 10, which is the date 10 days after the date of the c1 table, and all other values will be recalculated

c1.add(Calendar.DATE, 10);

Subtract the date of the c1 object by 10, which is the date of 10 days before the date of the c1 table, and all other values are recalculated

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

The meaning of the add of other field properties and so on

The obtained information for the Calendar class object

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);

Gregorian Calendar class

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

Calendar's getInstance() method returns a Gregorian Calendar object that is initialized by default with the current language environment and time zone. G regorian Calendar defines two fields: AD and BC. T hese represent two eras defined by the Gregorian calendar.

Here are a few ways to construct the Gregian Calendar object:

Serial number Constructors and descriptions
1 GregorianCalendar()
Construct a default Gregorian Calendar with the current time in the default time zone with the default locale.
2 GregorianCalendar(int year, int month, int date)
Construct a Gregorian Calendar with a given date setting in the default time zone with the default locale
3 GregorianCalendar(int year, int month, int date, int hour, int minute)
Construct a Gregorian Calendar with a 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)
Construct a Gregorian Calendar with a given date and time setting for the default time zone with the default locale.
5 GregorianCalendar(Locale aLocale)
Construct a Gregorian Calendar based on the current time in the default time zone with a given language environment.
6 GregorianCalendar(TimeZone zone)
Construct a Gregorian Calendar based on the current time in a given time zone with the default language environment.
7 GregorianCalendar(TimeZone zone, Locale aLocale)
Construct a Gregorian Calendar based on the current time in a given time zone with a given language environment.

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

Serial number Methods and instructions
1 void add(int field, int amount)
According to calendar rules, the specified (signed) amount of time is added to a given calendar field.
2 protected void computeFields()
Convert the UTC millisecond value to a time domain value
3 protected void computeTime()
Overwriting Calendar, the conversion time domain value is the UTC millisecond value
4 boolean equals(Object obj)
Compare this Gregorian Calendar with the specified Object.
5 int get(int field)
Gets the time value of the specified field
6 int getActualMaximum(int field)
Returns the current date, the maximum value of a given field
7 int getActualMinimum(int field)
Returns the current date, the minimum value of a given field
8 int getGreatestMinimum(int field)
Returns the highest minimum value for a given calendar field for this Gregorian Calendar instance.
9 Date getGregorianChange()
Get the changed date of the Gregory calendar.
10 int getLeastMaximum(int field)
Returns the lowest maximum value for a given calendar field for this Gregorian Calendar instance
11 int getMaximum(int field)
Returns the maximum value of a given calendar field for this Gregorian Calendar instance.
12 Date getTime()
Gets the current time of the calendar.
13 long getTimeInMillis()
Gets the current time of the calendar in long form
14 TimeZone getTimeZone()
Gets the time zone.
15 int getMinimum(int field)
Returns the minimum value for a given field.
16 int hashCode()
Rewrite hashCode.
17 boolean isLeapYear(int year)
Determines whether a given year is a leap year.
18 void roll(int field, boolean up)
Add or subtract (up/down) a single time unit from a given time field without changing the larger field.
19 void set(int field, int value)
Set the time field with a given value.
20 void set(int year, int month, int date)
Set the values for the year, month, and day.
21 void set(int year, int month, int date, int hour, int minute)
Set the values for year, month, day, hour, and minute.
22 void set(int year, int month, int date, int hour, int minute, int second)
Set the values for year, month, day, hour, minute, and second.
23 void setGregorianChange(Date date)
Set the change date for Gregorian Calendar.
24 void setTime(Date date)
Set the current time of Calendar with a given date.
25 void setTimeInMillis(long millis)
Set calendar's current time in a given long millisecond.
26 void setTimeZone(TimeZone value)
Set the current time zone with a given time zone value.
27 String toString()
Returns a string that represents the calendar.

Instance

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;
      // 初始化 Gregorian 日历
      // 使用当前时间和日期
      // 默认为本地时间和时区
      GregorianCalendar gcalendar = new GregorianCalendar();
      // 显示当前时间和日期的信息
      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));
      
      // 测试当前年份是否为闰年
      if(gcalendar.isLeapYear(year)) {
         System.out.println("当前年份是闰年");
      }
      else {
         System.out.println("当前年份不是闰年");
      }
   }
}

The above examples compile and run as follows:

Date: Apr 22 2009
Time: 11:25:27
当前年份不是闰年

For a complete list of Calender classes, you can refer to the standard Java documentation.