java.util tools such as Date, Calendar, GregorianCalendar, TimeZone, SimpleTimeZone, Locale

JDK8 Online Api Chinese Manual

JDK8 Online Api English Manual

java.util tools such as Date, Calendar, GregorianCalendar, TimeZone, SimpleTimeZone, Locale

Date class

   The Date class encapsulates the current date and time. Compared with the original Date class defined in Java 1.0, the Date class has undergone essential changes. When Java 1.1 was released, many of the functions defined by the original Date class were moved into the Calendar and DateFormat class classes. Therefore, many methods in the original Date class in Java 1.0 have been deprecated. For new code, you should not use the deprecated Java 1.0 methods, these methods are not introduced here.
   The Date class supports the following constructors:

Date()
Date(long millisec)

   The first constructor initializes the object with the current date and time. The second constructor accepts a parameter that is equal to the number of milliseconds since midnight on January 1, 1970. Table 1 shows the methods defined by the Date class that are still favored. The Date class also implements the Comparable interface.

Table 1 Methods still defined in the Date class
method Description
boolean after(Date date) Returns true if the date contained in the call Date object is later than the date specified by date; otherwise returns false
boolean before(Date date) Returns true if the date contained in the call Date object is earlier than the date specified by date; otherwise returns false
Object clone() Copy call Date object
int compareTo(Date date) Compare the date contained in the call object with the date specified by date. If the two are the same, it returns 0; if the calling object is earlier than date, it returns a negative value; if the calling object is later than date, it returns an integrity
boolean equals(Object date) Returns true if the date and time contained in the call Date object is the same as the date and time specified by date; otherwise returns false
static Date from(Instant t) Returns the Date object corresponding to the Instant object passed in t (new in JDK8)
long getTime() Returns the number of milliseconds that have elapsed since midnight on January 1, 1970
int hashCode() Returns the hash code of the calling object
void setTime(long time) Set the date and time to the value specified by time, time is the number of milliseconds that have elapsed since midnight on January 1, 1970
Instant toInstant() Returns the Instant object corresponding to the calling Date object (new in JDK8)
String toString() Convert the calling Date object to a string and return the result

   It can be seen by examining Table 1 that the Date feature, which is still in favor, does not allow obtaining a single component of date or time. As the following program lock demonstrates, you can only get the date and time in milliseconds, or return the default string representation of the date and time through the toString () method, or (starting from JDK8) as an Instant object to get the date and time In order to obtain more detailed information about the date and time, you need to use the Calendar class.

//Show date and time using only Date methods.
import java.util.Date;
class DateDemo {
    public static void main(String[] args) {
        //Instantiate a Date object
        Date date = new Date();
        //display time and date using toString()
        System.out.println(date);
        //Display number of milliseconds since midnight,January 1,1970 GMT
        long msec = date.getTime();
        System.out.println("Milliseconds since Jan. 1,1970 GMT = "+msec);
        /**
         * 输出:
         * Sat Feb 08 15:23:47 CST 2020
         * Milliseconds since Jan. 1,1970 GMT = 1581146627936
         */
    }
}
Calendar class

   The Calendar abstract class provides a set of methods that allow time in the form of milliseconds to be converted into a large number of useful time components. Some examples of such information that can be provided are years, months, days, hours, minutes, and seconds. Calendar subclasses will provide functions to interpret time information according to their own rules. This is an aspect of the Java class library that enables us to write programs that run in an international environment. A GregorainCalendar of this subclass.
   Note that
   JDK8 defines a new date and time API in java.time.
   The Calendar class does not provide a public constructor. The Calendar class defines several protected instance variables. areFieldsSet is a Boolean variable that indicates whether the time component is set. fields is an int array, used to save time components. isSet is a Boolean array indicating whether a specific time component is set. time is a long integer variable used to save the current time of this object. isTimeSet is a Boolean variable that indicates whether the current time is set.

Table 2 Common methods defined by the Calendar class
method Description
abstract void add(int which,int val) Add val to the time or date component specified by which. If you want to perform a subtraction operation, you can add a negative value. which must be one of the domain variables defined by the Calendar class, such as Calendar.HOUR
boolean after(Object calendarObj) If the call to the Calendar object contains a date later than the date specified by calendarObj, return true; otherwise return false
boolean before(Object calendarObj) Returns true if the date contained in the call to the Calendar object is earlier than the date specified by calendarObj; otherwise returns false
final void clear() Zero all time components contained in the call object
final void clear(int which) Clear the time component specified by which in the call object to zero
Object clone() Returns a copy of the calling object
boolean equals(Object clendarObj) If the date contained in the call to the Calendar object is the same as the date specified by calendarObj, return true; otherwise return false
int get(int calendarField) Returns the value of a time component in the calling object, which is specified by calendarField. The components that can be returned include Calendar.YEAR, Calendar.MONTH, Calendar.MINUTE, etc.
static Locale[] getAvailableLocales() Returns an array of Locale objects, which contains information about the regions where the calendar can be used
static Calendar getInstance() Calendar object for default region and time zone
static Calendar getInstance(TimeZone tz) The Calendar object is returned for the time zone specified by tz. Use default region
static Calendar getInstance(Locale locale) The Calendar object is returned for the area specified by the locale. Use default time zone
static Calendar getInstance(TimeZone tz,Locale locale) Returns the Calendar object for the time zone specified by tz and the area specified by locale
final Date getTime() Returns the Date object at the same time as the calling object
TimeZone getTimeZone() Returns the time zone of the calling object
final boolean isSet(int which) Returns true if the specified time component is set; otherwise returns false
void set(int which,int val) In the call object, set the date or time specified by which to the value specified by val. which must be one of the domain variables defined by Calendar, such as Calendar.HOUR
final void set(int year,int month,int dayOfMonth) 设置调用对象的各种日期和时间组成部分
final void set(int year,int month,int dayOfMonth,int hours,int minutes) 设置调用对象的各种日期和时间组成部分
final void set(int year,int month,int dayOfMonth,int hours,int minutes,int seconds) 设置调用对象的各种日期和时间组成部分
final void setTime(Date d) 设置调用对象的各种日期和时间组成部分。信息是从Date对象d中获取的
void setTimeZone(TimeZone tz) 将调用对象的时区设置为tz指定的时区
final Instant toInstant() 返回与调用Calendar实例对应的Instant对象(JDK8新增)

   Calendar类定义了以下int型常量,当获取或设置日历的组成部分时,需要用到这些常量,带有FOTMAT和STANDALONE后缀的都是JDK8新增的常量:

ALL_STYLES HOUR_OF_DAY PM
AM JANUARY SATURDAY
AM_PM JULY SECOND
APRIL JUNE SEPTEMBER
AUGUST LONG SHORT
DATE LONG_FORMAT SHORT_FORMAT
DAY_OF_MONTH LONG_STANDALONE SHORT_STANDALONE
DAY_OF_WEEK MARCH SUNDAY
DAY_OF_WEEK_IN_MONTH MAY THURSDAY
DAY_OF_YEAR MILLISECOND TUESDAY
DECEMEBER MINUTE UNDECIMBER
DST_OFFSET MONDAY WEDNESDAY
ERA MONTH WEEK_OF_MONTH
FEBRUARY NARROW_FORMAT WEEK_OF_YEAR
FIELD_COUNT NARROW_STANDALONE YEAR
FRIDAY NOVEMBER ZONE_OFFSET
HOUR OCTOBER

   下面的程序演示了Calendar类的一些方法:

//Demonstrate Calendar
import java.util.Calendar;
class CalendarDemo {
public static void main(String[] args) {
      String months[]={
              "Jan","Feb","Mar","Apr",
              "May","Jun","Jul","Aug",
              "Sep","Oct","Nov","Dec"
      };
      //Create a calendar initialized with the
      //current date and time int the default
      //locale and timezone.
      Calendar calendar = Calendar.getInstance();
      //Display current and date information.
      System.out.print("Date: ");
      System.out.print(months[calendar.get(Calendar.MONTH)]);
      System.out.print(" "+calendar.get(Calendar.DATE)+" ");
      System.out.println(calendar.get(Calendar.YEAR));
      System.out.print("Time: ");
      System.out.print(calendar.get(Calendar.HOUR)+":");
      System.out.print(calendar.get(Calendar.MINUTE)+":");
      System.out.println(calendar.get(Calendar.SECOND));
      //Set the time and date information and display it.
      calendar.set(Calendar.HOUR,20);
      calendar.set(Calendar.MINUTE,20);
      calendar.set(calendar.SECOND,20);
      System.out.print("Updated time: ");
      System.out.print(calendar.get(Calendar.HOUR)+":");
      System.out.print(calendar.get(Calendar.MINUTE)+":");
      System.out.println(calendar.get(Calendar.SECOND));
      /**
       * 输出:
       * Date: Feb 8 2020
       * Time: 4:47:17
       * Updated time: 8:20:20
       */
  }
}
GregorianCalendar 类

   GregorainCalendar类是Calendar类的具体实现,实现了Gregorain日历。Calendar类的getInstance()方法通常会返回一个GregorainCalendar对象,这个对象使用默认地区和时区下的当前日期和时间进行初始化。
   GregorainCalendar定义了两个域变量:AD和BC。它们表示格林尼治日历定义的两个纪元。
   GregorainCalendar对象还有几个构造函数。默认构造函数GregorainCalendar()使用默认地区和时区下的当前日期和时间进行初始化。还有以下3个构造函数可以指定其他信息:

GregorainCalendar(int year,int month,int dayOfMonth)
GregorainCalendar(int year,int month,int dayOfMonth,int hours,int minutes)
GregorainCalendar(int year,int month,int dayOfMonth,int hours,int minutes,int seconds)

   所有这3个版本都设置年、月和日。其中,year指定了年。月是由month指定的,0表示1月。月份中的日期是由dayofMonth指定的。第1个版本中奖时间设置为午夜,第2个版本中还设置了小时和分钟,第3个版本添加了秒。
   可以通过指定地区和/或时区来构造GregorainCalendar对象。使用如下构造函数创建的对象,将使用指定时区和/或地区下的当前时间进行初始化:

GregorainCalendar(Locale locale)
GregorainCalendar(TimeZone timeZone)
GregorainCalendar(TimeZone timeZone,Locale locale)

   GregorainCalendar实现了Calendar中的所有抽象方法,另外还提供了一些附加方法,如isLeapYear(),该方法测试某年是否是闰年,形式如下:

boolean isLeapYear(int year)

   如果year是闰年,该方法就返回true;否则返回false。JDK8还添加了以下方法:fro()和toZoneDateTime(),用于支持新的日期和时间API;getCalendarType(),它将日历类型作为一个字符串返回,即"gregory"。
   下面的程序演示了GregorainCalendar类:

//Demonstrate GregorianCalendar类:
import java.util.Calendar;
import java.util.GregorianCalendar;
class GregorianCalendarDemo {
 public static void main(String[] args) {
      String months[]={
              "Jan","Feb","Mar","Apr",
              "May","Jun","Jul","Aug",
              "Sep","Oct","Nov","Dec"
      };
      int year;
      //Create a Gregorian calendar initialized
      //with the current date and time in the
      //default locale and timezone.
      GregorianCalendar gcalendar = new GregorianCalendar();
      //Display current time anf 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");
      }
      /**
       * 输出:
       * Date: Feb 8 2020
       * Time: 5:23:12
       * The current year is a leap year
       */
  }
}
TimeZone 类

   另外一个与时间相关的类是TimeZone。TimeZone抽象类可以处理与格林尼治标准时间(Greenwich Mean Time,GMT)——也就是世界时间(Universal Time Coordinated,UTC)之间的时差。另外还能够计算夏令时。TimeZone只支持一个默认构造函数。

表3 TimeZone类定义的一些方法
方 法 描 述
Object clone() 返回特定于TimeZone的clone版本
static String[] getAvailableDs() 返回一个表示所有时区名称的String对象数组
static String[] getAvailableIDs(int timeDelta) 返回一个String对象数组,表示与GMT时差为timeDelta的所有时区名称
static TimeZone getDefault() 返回一个表示宿主计算机默认时区的TimeZone对象
String getID() 返回调用TimeZone对象的名称
abstract int getOffset(int era,int year,int month,int dayOfMonth,int dayOfWeek,int millisec) 返回计算当地时间时需要添加到GMT的时差,这个值会针对夏令时进行调整,该方法的参数表示日期和时间的组成部分
abstract int getRawOffset() 返回计算当地时间时需要添加到GMT的原始时差(使用毫秒表示),这个值不会针对夏令时进行调整
static TimeZone getTimeZone(String tzName) 为名为tzName的时区返回TimeZone对象
abstract boolean inDaylightTime(Date d) 如果日期d在调用对象的夏令时范围之内,就返回true;否则返回false
static void setDefault(TimeZone tz) 设置当前主机使用的默认时区,tz是将要使用的TimeZone对象的引用
void setID(String tzName) 将时区的名称(即时区的ID)设置为tzName指定的名称
abstract void setRawOffset(int millis) 以毫秒为单位设置与GMT之间的时差
ZoneId toZoneId() 将调用对象转换为ZoneId,并返回结果。ZoneId定义在java.time包中(JDK8新增)
abstract boolean useDaylightTime() 如果调用对象使用夏令时,就返回true;否则返回false
SimpleTimeZone 类

   SimpleTimeZone类是TimeZone的一个便利子类。它实现了TimeZone的抽象方法,并且可以操作Gregorian日历的时区,此外还能够计算夏令时。
   SimpleTimeZone类定义了4个构造函数,其中一个如下:

SimpleTimeZone(int timeDelta,String tzName)

   这个构造函数创建一个SimpleTimeZone对象,这个对象相对于格林尼治标准时间(GMT)的时差是timeDelta,时区名称为tzName。
   第2个SimpleTimeZone构造函数如下:

SimpleTimeZone(int timeDelta,String tzId,int dstMonth0,int dstDayInMonth0,int dstDay0,int time0,int dstMonth1,int dstDayInMonth1,int dstDay1,int time1)

   其中,相对于GMT的时差是由timeDelta指定的。时区名称是由tzID传入的。夏令时的开始时间是由参数dstMonth0,dstDayInMonth0,dstDay0和time0指定的。夏令时的结束时间是由参数dstMonth1、dstDayInMonth1、dstDay1和time1指定的。
   第3个SimpleTimeZone构造函数如下:

SimpleTimeZone(int timeDelta,String tzId,int dstMonth0,int dstDayInMonth0,int dstDay0,int time0,int dstMonth1,int dstDayInMonth1,int dstDay1,int time1,int dstDelta)

   其中,dstDelta是夏令时期间节约的毫秒数。
   第4个SimpleTimeZone构造函数如下:

SimpleTimeZone(int timeDelta,String tzId,int dstMonth0,int dstDayInMonth0,int dstDay0,int time0,int time0mode,int dstMonth1,int dstDayInMonth1,int dstDay1,int time1,int time1mode,int dstDelta)

   其中,time0mode指定了开始时间的模式,time1mode指定了结束时间的模式。有效的模式值包括:STANDARD_TIME、WALL_TIME、UTC_TIME
   时间模式指示如何解释时间。其他构造函数默认模式WALL_TIME。

Locale 类

   使用Locale类实例化的对象,用于描述地理或文化上的区域。Locale类是为数不多的几个类之一,使用这几个类可以编写能够在不同国际化环境中运行的Java程序。例如在不同的区域,用于显示日期、时间和数字的格式是不同的。
   国际化是一个很大的主题。但是,许多程序只需要处理基本问题,包括设置当前地区。
   Locale类定义了以下常量,对于应对大部分常见地区来说,这些常量是有用的:

CANADA GERMAN KOREAN
CANADA_FRENCH GERMANY PRC
CHINA ITALIAN SIMPLIFIED_CHINESE
CHINESE ITALY TAIWAN
ENGLISH JAPAN TRADITIONAL_CHINESE
FRANCE JAPANESE UK
FRENCH KOREA US

   例如,表达式Locale.CANADA是表示加拿大地区的Locale对象。
   Locale类的构造函数如下:

Locale(String language)
Locale(String language,String country)
Locale(String language,String country,String variant)

   这些构造函数用来构建表示特定语言以及特定国家(对于后面两个构造函数)的Locale对象。这些值必须包含标准语言和国家代码。辅助信息可以通过variant提供。
   Locale类定义了一些方法。其中最重要的方法之一是setDefault(),如下所示:

static void setDefault(Locale localeObj)

   下面是其他一些方法:

final String getDisplayCountry()
final String getDisplayLanguage()
final String getDisplayName()

   这些方法返回人类能够阅读的字符串,这些字符串用于显示国家的名称、语言的名称以及地区的完整描述。
   使用getDefault()方法可以获取默认地区,如下所示:

static Locale getDefault()

   JDK7对Locale类进行了重要升级、新的Locale类能够支持互联网工程任务组BCP47和Unicode技术标准35,其中前者定义了用来标识语言的标签,后者定义了地区数据标记语言。对BCP47和UTS35的支持导致为Locale类添加了几种特性,包括一些新方法和Locale.Builder类。在这些新特性中,新方法包括getScript()和toLanguageTag(),前者获取地区的脚本,后者获取包含地区语言标签的字符串。Locale.Builder类来构造Locale实例,确保地区说明被很好地根据BCP47定义的要求进行了形式化(Locale构造函数没有提供这一检查)。JDK8也为Locale类添加了一些方法,以支持筛选。扩展和查找等操作。
   Calendar和GregorianCalendar是以地区敏感方式使用的类的例子。DateFormat和SimpleDateFormat也依赖于地区。

发布了59 篇原创文章 · 获赞 20 · 访问量 3636

Guess you like

Origin blog.csdn.net/qq_34896730/article/details/104223282