[Java] Java-based date processing

Date processing based on java

java date time

​ The java.util package provides the Date class to encapsulate the current date and time.

The constructor of the Date class:

  • Use the current date and time to initialize the object.

  • Date();
    
  • Receive a parameter which is the number of milliseconds since January 1, 1970.

  • Date(long millisec)
    

Related methods of Date class:

Serial number Method and description
1 boolean after(Date date) returns true if the Date object calling this method is after the specified date, otherwise it returns false.
2 boolean before(Date date) returns true if the Date object calling this method is 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 the specified date. Return 0 when the two are equal. The 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 obj is Date type, the operation is equivalent to compareTo(Date). Otherwise it throws ClassCastException.
6 boolean equals(Object date) returns true 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 January 1, 1970 00:00:00 GMT.
8 int hashCode() returns the hash code value of this object.
9 void setTime(long time) Set the time and date in milliseconds since January 1, 1970 00:00:00 GMT.
10 String toString() converts this Date object into 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).

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, 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.

Format date:

  • Use the SimpleDateFormat class to format the date:

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

Date and time formatting code:

letter description Example
G Epoch mark AD
and Four years 2001
M month July or 07
d Day of the month 10
h AM/PM (1~12) format hour 12
H Hour of the day (0~23) 22
m Minutes 30
s Seconds 55
S Milliseconds 234
E Day of the week Tuesday
D Day of the year 360
F Day of the week of the month 2 (second Wed. in July)
w Week of the year 40
W The first few weeks of the month 1
a AM/PM mark PM
k Hour of the day (1~24) 24
K AM/PM (0~11) format hour 10
with Time zone Eastern Standard Time
Text delimiter Delimiter
" apostrophe `

  • Use printf to format the date:

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

转 换 符 说 明 示 例
c 包括全部日期和时间信息 星期六 十月 27 14:21:20 CST 2007
F "年-月-日"格式 2007-10-27
D "月/日/年"格式 10/27/07
r "HH:MM:SS PM"格式(12时制) 02:25:51 下午
T "HH:MM:SS"格式(24时制) 14:28:16
R "HH:MM"格式(24时制) 14:28
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);  
  }
}

解析字符串为时间

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

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

以上实例编译运行结果如下:

$ 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

测量时间:

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

Calendar类

Calendar类是一个抽象类,在实际使用时实现特定的子类的对象,创建对象的过程对程序员来说是透明的,只需要使用getInstance方法创建即可。

  • 默认当前日期:

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

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

Calendar类对象字段类型

常量 描述
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 星期几

  • 把 c1对象代表的日期设置为10号,其它所有的数值会被重新计
c1.set(Calendar.DATE,10);
  • 把c1对象代表的年份设置为2008年,其他的所有数值会被重新计算
c1.set(Calendar.YEAR,2008);
  • 把c1对象的日期加上10,也就是c1也就表示为10天后的日期,其它所有的数值会被重新计算
c1.add(Calendar.DATE, 10);
  • 把c1对象的日期减去10,也就是c1也就表示为10天前的日期,其它所有的数值会被重新计算
c1.add(Calendar.DATE, -10);

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类的一个具体实现。

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

序号 构造函数和说明
1 GregorianCalendar() 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。
2 GregorianCalendar(int year, int month, int date) 在具有默认语言环境的默认时区内构造一个带有给定日期设置的 GregorianCalendar
3 GregorianCalendar(int year, int month, int date, int hour, int minute) 为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。
4 GregorianCalendar(int year, int month, int date, int hour, int minute, int second) 为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。
5 GregorianCalendar(Locale aLocale) 在具有给定语言环境的默认时区内构造一个基于当前时间的 GregorianCalendar。
6 GregorianCalendar(TimeZone zone) 在具有默认语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。
7 GregorianCalendar(TimeZone zone, Locale aLocale) 在具有给定语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。

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

序号 方法和说明
1 void add(int field, int amount) 根据日历规则,将指定的(有符号的)时间量添加到给定的日历字段中。
2 protected void computeFields() 转换UTC毫秒值为时间域值
3 protected void computeTime() 覆盖Calendar ,转换时间域值为UTC毫秒值
4 boolean equals(Object obj) 比较此 GregorianCalendar 与指定的 Object。
5 int get(int field) 获取指定字段的时间值
6 int getActualMaximum(int field) 返回当前日期,给定字段的最大值
7 int getActualMinimum(int field) 返回当前日期,给定字段的最小值
8 int getGreatestMinimum(int field) 返回此 GregorianCalendar 实例给定日历字段的最高的最小值。
9 Date getGregorianChange() 获得格里高利历的更改日期。
10 int getLeastMaximum(int field) 返回此 GregorianCalendar 实例给定日历字段的最低的最大值
11 int getMaximum(int field) 返回此 GregorianCalendar 实例的给定日历字段的最大值。
12 Date getTime() 获取日历当前时间。
13 long getTimeInMillis() 获取用长整型表示的日历的当前时间
14 TimeZone getTimeZone() 获取时区。
15 int getMinimum(int field) 返回给定字段的最小值。
16 int hashCode() 重写hashCode.
17 boolean isLeapYear(int year) 确定给定的年份是否为闰年。
18 void roll(int field, boolean up) 在给定的时间字段上添加或减去(上/下)单个时间单元,不更改更大的字段。
19 void set(int field, int value) 用给定的值设置时间字段。
20 void set(int year, int month, int date) 设置年、月、日的值。
21 void set(int year, int month, int date, int hour, int minute) Set the value of year, month, day, hour, and minute.
22 void set(int year, int month, int date, int hour, int minute, int second) Set the value of year, month, day, hour, minute, and second.
23 void setGregorianChange(Date date) Set the change date of GregorianCalendar.
24 void setTime(Date date) Set the current time of the Calendar with the given date.
25 void setTimeInMillis(long millis) Set the current time of Calendar with the given long milliseconds.
26 void setTimeZone(TimeZone value) Set the current time zone with the given time zone value.
27 String toString() returns a string representing the calendar.
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("当前年份不是闰年");
      }
   }
}

operation result:

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

Note: The month of Calender starts from 0, but the date and year both start from 1.






*Disclaimer: This blog post is a personal study note, referring to the rookie tutorial and other network resources, if there is any infringement, please let us know by private message! *

Guess you like

Origin blog.csdn.net/qq_42380734/article/details/105360215