Home  >  Article  >  Java  >  How to use the Date date and time class in Java

How to use the Date date and time class in Java

王林
王林forward
2023-05-10 17:25:062305browse

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 that is from 1970 Number of milliseconds since January 1, year .

Date(long millisec)

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

##5int compareTo(Object obj). If obj is a Date type, the operation is equivalent to compareTo(Date). Otherwise it throws ClassCastException6boolean equals(Object date), returns true when the Date object calling this method is equal to the specified date, otherwise returns false7long getTime( ), returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT8int hashCode( ), returns the hash code value of this object 9void setTime(long time), set the time and date using the number of time milliseconds since January 1, 1970 00:00:00 GMT10String toString(), put This Date object is converted to a String of the following form: dow mon dd hh:mm:ss zzz yyyy where: dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
Serial number Method description
1 boolean after(Date date), if the Date object calling this method returns true after the specified date, otherwise it returns false
2 boolean before(Date date), if the Date object calling this method returns true before the specified date, otherwise it returns false
3 Object clone( ), returns a copy of this object
4 int compareTo(Date date), compares the Date object when this method is called with Specify the date. 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

For example, get the current date and time and print :

import java.util.Date;
  
public class DateDemo {
   public static void main(String[] args) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 使用 toString() 函数显示日期时间
       System.out.println(date.toString());
   }
}
// 实例编译运行结果如下:
// Tue Apr 04 22:50:40 CST 2023

Date comparison

Java uses the following three methods To compare two dates:

  • Use the getTime() method to obtain 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-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 ("yyyy-MM-dd hh:mm:ss");
 
      System.out.println("当前时间为: " + ft.format(dNow));
   }
}
// 实例编译运行结果如下:
// 当前时间为: 2023-04-04 10:55:24

SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); This line of code establishes the conversion format, where yyyy is the complete AD year, MM is the month, dd is the date, HH:mm:ss is the hour, minute, and second.

Note: Some formats are uppercase, and some formats are lowercase. For example, MM is the month, mm is the minute; HH is the 24-hour format, and hh is the 12-hour format.

Date and time format 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:

LetterDescriptionExampleGEra markAD##yMdhHmsSEDFwW##aA.M./P.M. MarkPMkHour of the day (1~24)24KA.M./P.M. (0~11) format hour10zTime zoneEastern Standard Time'Text delimiterDelimiter "Single quotes`

使用printf格式化日期

printf 方法可以很轻松地格式化时间和日期。使用两个字母格式,它以 %t 开头并且以下面表格中的一个字母结尾。

  • %tY:输出四位数的年份,例如:2023

  • %ty:输出两位数的年份,例如:23

  • %tm:输出两位数的月份,例如:02

  • %tB:输出月份的全名,例如:February

  • %tb:输出月份的缩写,例如:Feb

  • %tA:输出星期的全名,例如:Wednesday

  • %ta:输出星期的缩写,例如:Wed

  • %td:输出两位数的日期,例如:24

  • %te:输出一位或两位数的日期,例如:24 或 02

  • %tH:输出24小时制的小时数,例如:23

  • %tI:输出12小时制的小时数,例如:11

  • %tM:输出分钟数,例如:45

  • %tS:输出秒数,例如:30

  • %tp:输出上午还是下午,例如:AM 或 PM

  • %tZ:输出时区,例如:GMT+08:00

Four-digit year 2001
month July or 07
Date of the month 10
A.M./P.M. (1~12) format hour 12
Hour of the day (0~23) 22
Minutes 30
Seconds 55
Milliseconds 234
Day of the week Tuesday
Days of the year 360
The number of weeks in the month What number 2 (second Wed. in July)
The number of weeks in the year 40
Week of the month 1
转换符 说明 示例
%tc 包括全部日期和时间信息 星期六 十月 27 14:21:20 CST 2007
%tF "年-月-日"格式 2007-10-27
%tD "月/日/年"格式 10/27/07
%tr "HH:MM:SS PM"格式(12时制) 02:25:51 下午
%tT "HH:MM:SS"格式(24时制) 14:28:16
%tR "HH:MM"格式(24时制) 14:28

printf格式化日期实例

格式化日期:

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);
   }
}
// 执行输出结果为:
// 2023-04-05 09:59:23 CST

使用转换符格式化日期:

import java.util.Date;
 
public class DateDemo {
 
  public static void main(String[] args) {
     // 初始化 Date 对象
     Date date = new Date();
 
     //c的使用  
    System.out.printf("全部日期和时间信息:%tc%n",date);          
    //f的使用  
    System.out.printf("年-月-日格式:%tF%n",date);  
    //d的使用  
    System.out.printf("月/日/年格式:%tD%n",date);  
    //r的使用  
    System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);  
    //t的使用  
    System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);  
    //R的使用  
    System.out.printf("HH:MM格式(24时制):%tR",date);  
  }
}
// 实例编译运行结果如下:
// 全部日期和时间信息:星期三 四月 05 10:06:21 CST 2023
// 年-月-日格式:2023-04-05
// 月/日/年格式:04/05/23
// HH:MM:SS PM格式(12时制):10:06:21 上午
// HH:MM:SS格式(24时制):10:06:21
// HH:MM格式(24时制):10:06

如果你需要重复提供日期,那么利用这种方式来格式化它的每一部分就有点复杂了。因此,可以利用一个格式化字符串指出要被格式化的参数的索引。索引必须紧跟在 % 后面,而且必须以 $ 结束。例如:

import java.util.Date;
  
public class DateDemo {
 
   public static void main(String[] args) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 使用toString()显示日期和时间
       // %1$索引指向 "Due date:"
       // %2$索引指向 date
       System.out.printf("%1$s %2$tB %2$td, %2$tY", 
                         "Due date:", date);
   }
}
// 实例编译运行结果如下:
// Due date: 四月 05, 2023

或者,你可以使用 < 标志。它表明先前被格式化的参数要被再次使用。例如:

import java.util.Date;
  
public class DateDemo {
 
   public static void main(String[] args) {
       // 初始化 Date 对象
       Date date = new Date();
        
       // 显示格式化时间
       System.out.printf("%s %tB %

定义日期格式的转换符可以使日期通过指定的转换符生成新字符串。这些日期转换符如下所示:

import java.util.*;
  
public class DateDemo {
   public static void main(String[] args) {
       Date date=new Date();                                      
        //b的使用,月份简称  
        String str=String.format(Locale.US,"英文月份简称:%tb",date);       
        System.out.println(str);                                                                              
        System.out.printf("本地月份简称:%tb%n",date);  
        //B的使用,月份全称  
        str=String.format(Locale.US,"英文月份全称:%tB",date);  
        System.out.println(str);  
        System.out.printf("本地月份全称:%tB%n",date);  
        //a的使用,星期简称  
        str=String.format(Locale.US,"英文星期的简称:%ta",date);  
        System.out.println(str);  
        //A的使用,星期全称  
        System.out.printf("本地星期的简称:%tA%n",date);  
        //C的使用,年前两位  
        System.out.printf("年的前两位数字(不足两位前面补0):%tC%n",date);  
        //y的使用,年后两位  
        System.out.printf("年的后两位数字(不足两位前面补0):%ty%n",date);  
        //j的使用,一年的天数  
        System.out.printf("一年中的天数(即年的第几天):%tj%n",date);  
        //m的使用,月份  
        System.out.printf("两位数字的月份(不足两位前面补0):%tm%n",date);  
        //d的使用,日(二位,不够补零)  
        System.out.printf("两位数字的日(不足两位前面补0):%td%n",date);  
        //e的使用,日(一位不补零)  
        System.out.printf("月份的日(前面不补0):%te",date);  
   }
}
// 输出结果为:
// 英文月份简称:Apr
// 本地月份简称:四月
// 英文月份全称:April
// 本地月份全称:四月
// 英文星期的简称:Wed
// 本地星期的简称:星期三
// 年的前两位数字(不足两位前面补0):20
// 年的后两位数字(不足两位前面补0):23
// 一年中的天数(即年的第几天):095
// 两位数字的月份(不足两位前面补0):04
// 两位数字的日(不足两位前面补0):05
// 月份的日(前面不补0):5

解析字符串为时间

SimpleDateFormat 类有一些附加的方法,特别是parse(),它试图按照给定的SimpleDateFormat 对象的格式化存储来解析字符串。例如:

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); 
      }
   }
}
// 实例编译运行结果如下:
// 1818-11-11 Parses as Wed Nov 11 00:00:00 CST 1818

休眠(sleep)

sleep()使当前线程进入停滞状态(阻塞当前线程),让出CPU的使用、目的是不让当前线程独自霸占该进程所获的CPU资源,以留一定时间给其他线程执行的机会。你可以让程序休眠一毫秒的时间或者到您的计算机的寿命长的任意段时间。例如,下面的程序会休眠3秒:

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!"); 
      }
   }
}
// 实例编译运行结果如下:
// Thu Apr 06 11:18:56 CST 2023
// Thu Apr 06 11:18:59 CST 2023

测量时间间隔(以毫秒为单位)的实例:\color{red}{测量时间间隔(以毫秒为单位)的实例 :}测量时间间隔(以毫秒为单位)的实例:

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!");
      }
   }
}
// 实例编译运行结果如下:
// Thu Apr 06 11:25:14 CST 2023
// Thu Apr 06 11:25:17 CST 2023
// Difference is : 3038

Calendar类

我们现在已经能够格式化并创建一个日期对象了,但是我们如何才能设置和获取日期数据的特定部分呢,比如说小时,日,或者分钟? 我们又如何在日期的这些部分加上或者减去值呢? 答案是使用Calendar 类。

Calendar类的功能要比Date类强大很多,但在实现方式上也比Date类要复杂一些。

Calendar类是一个抽象类,在实际使用时实现特定的子类的对象,创建对象的过程对程序员来说是透明的,只需要使用getInstance方法创建即可。例如创建一个代表系统当前日期的Calendar对象:

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

或者创建一个指定日期的Calendar对象(注:Calendar 的月份是从 0 开始的):

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

Calendar类对象字段类型:Calendar类中用以下这些常量表示不同的意义,jdk内的很多类其实都是采用的这种思想:

常量 描述
Calendar.YEAR 年份
Calendar.MONTH 月份
Calendar.DATE 日期
Calendar.DAY_OF_MONTH 日期,和上面的字段意义完全相同
Calendar.HOUR 12小时制的小时
Calendar.HOUR_OF_DAY 24小时制的小时
Calendar.MINUTE 分钟
Calendar.SECOND
Calendar.DAY_OF_WEEK 星期几

Calendar类对象信息的设置

set设置

调用 public final void set(int year,int month,int date) 方法。例如:

Calendar c1 = Calendar.getInstance();
c1.set(2009, 6, 12);//把Calendar对象c1的年月日分别设这为:2009、6、12

如果只设定某个字段,例如日期的值,则可以使用 public void set(int field,int value) 方法。例如,把 c1对象代表的日期设置为10号,其他的所有数值会被重新计算:

Calendar c1 = Calendar.getInstance();
c1.set(Calendar.DATE,10);

其他字段属性set的意义以此类推。

add设置

把c1对象的日期加上10,也就是c1也就表示为10天后的日期,其它所有的数值会被重新计算:

Calendar c1 = Calendar.getInstance();
c1.add(Calendar.DATE, 10);

把c1对象的日期减去10,也就是c1也就表示为10天前的日期,其它所有的数值会被重新计算:

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

其他字段属性的add的意义以此类推。

Calendar类对象信息的获得

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类

Calendar类实现了公历日历,GregorianCalendar是Calendar类的一个具体实现。Calendar 的getInstance()方法返回一个默认用当前的语言环境和时区初始化的GregorianCalendar对象。GregorianCalendar定义了两个字段:AD和BC。这是代表公历定义的两个时代。

下面列出GregorianCalendar对象的几个构造方法

  • GregorianCalendar() —— 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。

  • GregorianCalendar(int year, int month, int date) —— 在具有默认语言环境的默认时区内构造一个带有给定日期设置的 GregorianCalendar。

  • GregorianCalendar(int year, int month, int date, int hour, int minute) —— 为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。

  • GregorianCalendar(int year, int month, int date, int hour, int minute, int second) —— 为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。

  • GregorianCalendar(Locale aLocale) —— 在具有给定语言环境的默认时区内构造一个基于当前时间的 GregorianCalendar。

  • GregorianCalendar(TimeZone zone) —— 在具有默认语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。

  • GregorianCalendar(TimeZone zone, Locale aLocale) —— 在具有给定语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。

这里是GregorianCalendar 类提供的一些尝用的方法列表

  • void add(int field, int amount) —— 根据日历规则,将指定的(有符号的)时间量添加到给定的日历字段中。

  • protected void computeFields() —— 转换UTC毫秒值为时间域值。

  • protected void computeTime() —— 覆盖Calendar ,转换时间域值为UTC毫秒值。

  • boolean equals(Object obj) —— 比较此 GregorianCalendar 与指定的 Object。

  • int get(int field) —— 获取指定字段的时间值。

  • int getActualMaximum(int field) —— 返回当前日期,给定字段的最大值。

  • int getActualMinimum(int field) —— 返回当前日期,给定字段的最小值。

  • int getGreatestMinimum(int field) —— 返回此 GregorianCalendar 实例给定日历字段的最高的最小值。

  • Date getGregorianChange() —— 获得格里高利历的更改日期。

  • int getLeastMaximum(int field) —— 返回此 GregorianCalendar 实例给定日历字段的最低的最大值。

  • int getMaximum(int field) —— 返回此 GregorianCalendar 实例的给定日历字段的最大值。

  • Date getTime() —— 获取日历当前时间。

  • long getTimeInMillis() —— 获取用长整型表示的日历的当前时间。

  • TimeZone getTimeZone() —— 获取时区。

  • int getMinimum(int field) —— 返回给定字段的最小值。

  • int hashCode() —— 重写hashCode。

  • boolean isLeapYear(int year) —— 确定给定的年份是否为闰年。

  • void roll(int field, boolean up) —— 在给定的时间字段上添加或减去(上/下)单个时间单元,不更改更大的字段。

  • void set(int field, int value) —— 用给定的值设置时间字段。

  • void set(int year, int month, int date) —— 设置年、月、日的值。

  • void set(int year, int month, int date, int hour, int minute) —— 设置年、月、日、小时、分钟的值。

  • void set(int year, int month, int date, int hour, int minute, int second) —— 设置年、月、日、小时、分钟、秒的值。

  • void setGregorianChange(Date date) —— 设置 GregorianCalendar 的更改日期。

  • void setTime(Date date) —— 用给定的日期设置Calendar的当前时间。

  • void setTimeInMillis(long millis) —— 用给定的long型毫秒数设置Calendar的当前时间。

  • void setTimeZone(TimeZone value) —— 用给定时区值设置当前时区。

  • String toString() —— 返回代表日历的字符串。

GregorianCalendar 使用实例

mport 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("当前年份不是闰年");
      }
   }
}

// 实例编译运行结果如下:
// Date: Apr 6 2023
// Time: 3:35:13
// 当前年份不是闰年

方法实例:\color{red}{方法实例:}方法实例:

时间戳转换成时间

public class Test {
    public static void main(String args[]) {
        // 获取当前时间戳
        Long timeStamp = System.currentTimeMillis();
        // 时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 时间戳转换成时间
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
        System.out.println("格式化结果:" + sd);

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
        String sd2 = sdf2.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
        System.out.println("格式化结果:" + sd2);
    }
}

// 实例编译运行结果如下:
// 格式化结果:2023-04-23 14:24:13
// 格式化结果:2023 年 04 月 23 日 14 时 24 分 13 秒

The above is the detailed content of How to use the Date date and time class in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete