Java.util.Date and Java.util.Calendar and related classes

Source: Internet
Author: User
Tags time zones iso 8601 locale time and date time in milliseconds


Datedate represents a specific moment, accurate to milliseconds. Before JDK1.1, date has two other functions. It allows you to interpret dates as year, month, day, hour, minute, and second values. It also allows formatting and parsing of date strings. However, the APIs for these functions are not easy to internationalize. Starting with JDK1.1, you should use the Calendar class to implement conversion between date and Time fields, and use the DateFormat class to format and parse date strings. The appropriate method in date has been deprecated. Date uses UTC time, such as Thu June 17:12:57 CST 2016,CST, which represents the China standard times ut+8:00. Although the date class intends to reflect Coordinated Universal Time (UTC), it cannot be so accurate, depending on the host environment of the Java Virtual machine. Currently almost all operating systems assume 1 days = 24x60x60 = 86,400 seconds. For UTC, however, an additional second, called a leap second, occurs approximately every one or two years. Leap seconds is always incremented as the last second of the day and always increases on December 31 or June 30. For example, the last minute of 1995 is 61 seconds, because it adds a leap second. Most computer clocks are not particularly accurate and therefore do not reflect the difference in leap seconds.
Some computer standards are defined by Greenwich Mean Time (GMT), which is equal to GMT and world Time (UT). GMT is the standard "folk" name; UT is the "science" name of the same standard. The difference between UTC and UT is that UTC is based on atomic clocks, UT is based on celestial observations, and both are difficult to whatsoever in practical applications. Because the rotation of the Earth is not uniform (it slows down and accelerates in a complex way), UT is never evenly flowing. The leap seconds are introduced in UTC as needed to keep UTC within 0.9 seconds of UT1, and UT1 is the UT version with some corrections applied. There are other time and date systems; For example, the time scale used by the satellite-based Global Positioning System (GPS) is synchronized with UTC, but is not adjusted for leap seconds. Most of the date methods are obsolete and are replaced by the Calendar class method, and here are a few important methods: Construction method public Date ()
The current time. The public date (long date) allocates a Date object and initializes the object to represent the specified number of milliseconds since the standard base time, known as the epoch, or January 1, 1970 00:00:00 GMT. Example:
public static void main(String[] args) {
        System.out.println(new Date());//Thu Jan 01 08:00:00 CST 1970 CST表示UTC+8,所以是8点
    }
Other
The public boolean after (date time) tests whether this date is after the specified date. public Boolean before (date time) tests whether this date is before the specified date. The public int compareTo (date anotherdate) compares the order of two dates. A value of 0 is returned if the parameter date equals this date, or a value less than 0 if this date precedes the date parameter, or a value greater than 0 if this date is after the date parameter. public boolean equals (Object obj) compares the equality of two dates. The result is true when and only if the argument is not null and is a Date object that represents the same point in time (to milliseconds) as this object.
Therefore, these two objects are equal when and only if the GetTime method returns the same long value for two date objects.

Public long GetTime () returns the number of milliseconds represented by this date object since January 1, 1970 00:00:00 GMT. The public void settime (long time) sets this date object to represent a point-in 00:00:00 GMT after the January 1, 1970. The Timezonetimezone represents the time zone offset and can also calculate daylight savings.
Typically, you use Getdefault to get Timezone,getdefault to create timezone based on the time zone in which your program runs. For example, for programs running in Japan, Getdefault creates timezone objects based on Japanese standard time.
You can also get timezone with the gettimezone time zone ID. For example, the time zone ID for the US Pacific Time Zone is "america/los_angeles". Therefore, you can use the following statement to obtain the United States Pacific Time TimeZone object: TimeZone TZ = Timezone.gettimezone ("America/los_angeles");
You can use the Getavailableids method to iterate over all supported time zone IDs. You can choose a supported ID to get timezone. If you want a time zone that cannot be represented by one of the supported IDs, you can specify a custom time zone ID to generate the timezone. The syntax for customizing the time zone ID is: normalizedcustomid:
GMT Sign Twodigithours:minutes
Sign: one of the following
+ -
Twodigithours:
Digit Digit
Minutes:
Digit Digit
Digit: one of the following
0 1 2 3 4 5 6 7 8 9 For example, Timezone.gettimezone ("GMT-8"). GetID () returns "gmt-08:00". The hours must be between 0 and 23 and the minutes must be between 00 and 59. For example, "gmt+10" and "gmt+0010" respectively mean 10 hours and 10 minutes earlier than GMT. For compatibility with jdk1.1.x, some three-letter time zone IDs (such as "PST", "CTT", and "AST") are also supported. However, their use is discarded because the same abbreviations are often used in multiple time zones (for example, "CST" may be the United States "central Standard Time" and "China Standard Time"), but the Java platform can only recognize one of them. Example:
public static void main (String [] args) {
        TimeZone timeZone = TimeZone.getDefault ();
        System.out.println (timeZone.getDisplayName (true, TimeZone.LONG)); // China Daylight Saving Time
        System.out.println (timeZone.getDisplayName (false, TimeZone.LONG)); // China Standard Time
        System.out.println (timeZone.getDisplayName (true, TimeZone.SHORT)); // CDT
        System.out.println (timeZone.getDisplayName (false, TimeZone.SHORT)); // CST
        System.out.println (timeZone.getID ()); // Asia / Shanghai

        TimeZone timeZone1 = TimeZone.getTimeZone ("AST");
        System.out.println (timeZone1.getDisplayName (true, TimeZone.LONG)); // Alaska Daylight Saving Time
        System.out.println (timeZone1.getDisplayName (false, TimeZone.LONG)); // Alaska standard time
        System.out.println (timeZone1.getDisplayName (true, TimeZone.SHORT)); // AKDT
        System.out.println (timeZone1.getDisplayName (false, TimeZone.SHORT)); // AKST
        System.out.println (timeZone1.getID ()); / AST

        TimeZone timeZone2 = TimeZone.getTimeZone ("America / Los_Angeles");
        System.out.println (timeZone2.getDisplayName (true, TimeZone.LONG)); // Pacific Daylight Time
        System.out.println (timeZone2.getDisplayName (false, TimeZone.LONG)); // Pacific Standard Time
        System.out.println (timeZone2.getDisplayName (true, TimeZone.SHORT)); // PDT
        System.out.println (timeZone2.getDisplayName (false, TimeZone.SHORT)); // PST
        System.out.println (timeZone2.getID ()); // America / Los_Angeles

        TimeZone timeZone3 = TimeZone.getTimeZone ("GMT + 0010");
        System.out.println (timeZone3.getDisplayName (true, TimeZone.LONG)); // GMT + 00: 10
        System.out.println (timeZone3.getDisplayName (false, TimeZone.LONG)); // GMT + 00: 10
        System.out.println (timeZone3.getDisplayName (true, TimeZone.SHORT)); // GMT + 00: 10
        System.out.println (timeZone3.getDisplayName (false, TimeZone.SHORT)); // GMT + 00: 10
        System.out.println (timeZone3.getID ()); // GMT + 00: 10
    }
The  calendarcalendar class is an abstract class that provides methods for converting a particular moment to a set of calendar fields such as year, MONTH, Day_of_month, hour, and so on. and provides some methods for manipulating calendar fields, such as getting the date of the next week. The instantaneous value is expressed as a millisecond, which is the offset from the calendar element (that is, Greenwich Mean Time January 1, 1970, 00:00:00.000, Gregorian calendar). Because the calendar is an abstract class, it has multiple subclasses, such as GregorianCalendar (Gregorian or Japaneseimperialcalendar), and the JDK7.0 increase. As with other locale-sensitive classes, Calendar provides a class method, getinstance, to obtain a generic object of this type. The getinstance method of the Calendar returns an object of a calendar subclass whose calendar field has been initialized by the current date and time: public static calendar getinstance () returns the calendar based on the current time, The default time zone and default locale are used.  public static Calendar getinstance (Locale alocale) returns the calendar based on the current time, using the default time zone and the given locale.  public static calendar getinstance (TimeZone zone) returns the calendar based on the current time, used to the timing zone and the default locale.   public static Calendar getinstance (TimeZone Zone,locale alocale) returns the calendar based on the current time, using the given time zone and the given locale.  calendar uses two parameters to define a locale-specific 7-day week: The first day of the Week (FirstDayOfWeek): For example, in the United States, this day is Sunday, and in France, the day is Monday, in the Calendar class, China is also Sunday by default. Minimum number of days required for the first one weeks of the year (Minimaldaysinfirstweek): The range is 1-7. These numbers are taken from the locale in which the calendar was constructed. You can also explicitly specify them by using methods that set their values.   Get and set the Calendar field value you can set the Calendar field value by calling the Set method. In the needAll field value settings in the calendar are not interpreted until the time value (milliseconds elapsed from the calendar) or the Calendar field value is calculated. Calling get, Gettimeinmillis, GetTime, add, and roll involve such calculations.   Loose Calendar There are two modes of interpreting calendar fields, namely lenient and non-lenient. When the calendar is in lenient mode, it accepts values that are larger than the range of calendar fields that it generates. All calendar fields are normalized when the calendar recalculates the values of the Calendars field so that the values are returned by get (). For example, GregorianCalendar in lenient mode interprets MONTH = = January, Day_of_month = = 32 as February 1.  
When the calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its Calendar field. For example, GregorianCalendar always generates a day_of_month value between 1 and the length of the month. If you have set any field values that are out of range, GregorianCalendar in non-lenient mode throws an exception when calculating time or Calendar field values. public void Setlenient (Boolean lenient) can be set to loose. Calendar Field Resolution
When you calculate the date and time in a calendar field, there may not be enough information for the calculation (for example, only year and month, but no day), or there may be inconsistent information (such as "Tuesday, July 15, 1996" (GMT)-in fact, July 15, 1996 is Monday). calendar resolves the date and time in the following way.
If there are any conflicts in the Calendar field values, Calendar will give priority to the most recently set calendar fields. The following are the default combinations of calendar fields. The most recent combination determined by a single field that was recently set will be used.
Year + MONTH + day_of_month
Year + MONTH + week_of_month + day_of_week
Year + MONTH + day_of_week_in_month + day_of_week
Year + day_of_year
Year + Day_of_week + week_of_year
Hour_of_day
AM_PM + HOUR
If there is also any calendar field in the selected field combination that has not been set, the calendar will use its default value. The default values for each field may vary depending on the calendar system. For example, in GregorianCalendar, the default value of a field is the same as the field value in the beginning part of the calendar: Year = 1970, MONTH = January, Day_of_month = 1, and so on. Gregoriancalendargregoriancalendar is the most important subclass of the calendar and provides the standard calendar system used in most countries around the world. GregorianCalendar is a hybrid calendar that supports both the Julian calendar and the Gregorian calendar system with the support of a single discontinuity. Setgregorianchange (date date) sets the date on which the GregorianCalendar is changed. This is the point at which the date of the Gregorian calendar is changed from the Julian date. The default time is October 15, 1582 (Gregorian calendar). Until then, the dates were calculated according to the Julian calendar. To get a purely Julian calendar, you can set the change date to date (Long.max_value). To get a purely Gregorian calendar, you can set the change date to date (Long.min_value). Historically, in the countries where the Gregorian calendar was first adopted, the October 4, 1582 (Julian calendar) was followed by October 15, 1582 (Gregorian calendar). This calendar correctly simulates these changes. Before starting the Gregorian calendar, GregorianCalendar realized the Julian calendar. The only difference between the Gregorian and Julian calendars is the leap year rule. The Julian calendar specifies that every 4 years is a leap year, while the Gregorian calendar ignores the century that cannot be divisible by 400. Before the Gregorian calendar was created, the New Year was March 25. To avoid confusion, this calendar always uses January 1 as the New Year. If you want a date before the Gregorian calendar conversion and between January 1 and March 24, you can make manual adjustments.

The Week_of_year field values range from 1 to 53. The first week of the year begins at the earliest 7 days of Getfirstdayofweek () and contains at least getminimaldaysinfirstweek () days of the year. This depends on the value of Getminimaldaysinfirstweek (), Getfirstdayofweek (), and the day of the week January 1. Each week between the first week of the year and the one week of the following year is numbered sequentially from 2 to 52 or 53 (as required).
For example, January 1, 1998 is Thursday. If Getfirstdayofweek () is Monday and Getminimaldaysinfirstweek () is 4 (these values reflect ISO 8601 and many country/region standards), the first week of 1998 begins in December 1997 29th, ended on January 4, 1998. However, if Getfirstdayofweek () is Sunday, then the first week of 1998 begins on January 4, 1998 and ends on January 10, 1998, and 1998 years the first three days are part of the 53rd week of 1997.

The Week_of_month field values range from 0 to 6. The first week of one months (the date of Week_of_month = 1) is the earliest date of at least consecutive getminimaldaysinfirstweek () days of the month, ending with the day before Getfirstdayofweek (). Unlike the first week of the year, the first week of one months may be shorter than 7 days, and it does not have to start on the day of Getfirstdayofweek () and does not include the dates for the first one months. The week_of_month of the month's date before the first one weeks is 0.
For example, if Getfirstdayofweek () is Sunday,getminimaldaysinfirstweek () 4, then the first week of January 1998 is from Sunday January 4 to January 10 Saturday. The week_of_month of these days is 1. The week_of_month of Thursday January 1 to January 3 Saturday is 0. If Getminimaldaysinfirstweek () becomes 3, the week_of_month from January 1 to January 3 is 1.
The Clear method sets the Calendar field to undefined. GregorianCalendar Use the following default values for each calendar field (if the value is undefined).
Field Default value
ERA AD
Year 1970
MONTH January
Day_of_month 1
Day_of_week The first day of one weeks
Week_of_month 0
Day_of_week_in_month 1
am_pm Am
HOUR, Hour_of_day, MINUTE, SECOND, millisecond 0

Field action set (f, Value)   Change Calendar field F to value. Additionally, it sets an internal member variable to indicate that the Calendar field F has been changed. Although the Calendar field F is changed immediately, the time value of the calendar (in milliseconds) is not recalculated until the next call to get (), GetTime (), Gettimeinmillis (), add (), or roll (). Therefore, multiple calls to set () do not trigger multiple unnecessary computations. The result of changing a calendar field with set () is that other calendar fields may also change, depending on the Calendar field, the Calendar field value, and the calendar system. Example: Assume that GregorianCalendar was initially set to August 31, 1999. Call Set (Calendar.month, Calendar.september) to set the date to September 31, 1999. This is a temporary internal expression of October 1, 1999. The month is supposed to be October, but calling set (Calendar.day_of_month, 30) before calling GetTime () sets the date to September 30, 1999 because no recalculation occurred after the call set ().  add (f, Delta)   Add the delta to the F field. This is equivalent to calling set (F, Get (f) + delta). Unlike set (), add () forces the calendar system to recalculate the number of milliseconds in the calendar and all fields immediately. Add () has two rules: 1. The value of the F field after the call minus the value of the F field before the call equals the delta, the next larger field is incremented or decremented when the field F field value is out of range, and the field value is adjusted back to its extent. 2, if it is expected that a smaller field is immutable, but it is not possible to make it equal to the previous value, because after the change in the field F, or after the occurrence of other constraints, such as the time zone offset changes, its maximum and minimum value is also changed, and its value is adjusted to as close as possible to the desired value. A smaller field represents a smaller time cell, such as hour, which is a smaller field than Day_of_month. For smaller segments that do not expect to be invariant fields, no adjustments are required. The calendar system, such as the Gregorian calendar, determines which fields are expected to be the same. Example: Assume that GregorianCalendar was initially set to August 31, 1999. Call Add (Calendar.month, 13) to set the calendar to September 30, 2000. The Add Rule 1 month field is set to September because adding to AugustPlus 13 months is the next year's September. Because Day_of_month cannot be September 31 in GregorianCalendar, add Rule 2 sets Day_of_month to 30, which is the most likely value. Although Day_of_week is a smaller field, you cannot adjust the Day_of_week according to Rule 2, because the value also needs to change when the month in GregorianCalendar changes. This example can be understood as the last day of the month after the month is increased by 13 months.  roll (f, Delta)   adds the delta to the F field, which is equivalent to calling add (f, delta), but not changing the larger field. A larger field represents a larger time unit. Day_of_month is a field larger than hour. The difference between  add and roll was originally set to the GregorianCalendar of August 31, 1999. Now call Roll (Calendar.month, 8) to set the calendar to April 30, 1999. If you use GregorianCalendar, the April day_of_month field cannot be 31. Set Day_of_month to the closest possible value of 30. The year field remains at the value of 1999 because it is a larger field than month, so it cannot be changed.
Originally set to GregorianCalendar on Sunday, June 6, 1999. Now call Roll (Calendar.week_of_month,-1) to set the calendar to June 1, 1999 Tuesday, and call Add (Calendar.week_of_month,-1) to set the calendar to Sunday May 30, 1999 。 This is because the rise and fall rules impose other constraints: the Week_of_month changes when the month must be constant. The date must be between June 1 Tuesday and June 5 Saturday. Day_of_week (which is a invariant when changing week_of_month) is set to Tuesday, which is the closest possible value to Sunday (where Sunday is the first day of one weeks).

Construction method Public GregorianCalendar () constructs a default GregorianCalendar using the current time in the default time zone with the default locale.  public GregorianCalendar (TimeZone zone) constructs a GregorianCalendar based on the current time within a given time zone with a default locale.  public GregorianCalendar (Locale alocale) constructs a GregorianCalendar based on the current time in the default time zone with a given locale.  public GregorianCalendar (TimeZone zone,locale Alocale) constructs a GregorianCalendar based on the current time within a given time zone with a given locale.  public GregorianCalendar (int year,int month, int dayofmonth) Constructs a gregoriancalendar with the given date setting in the default time zone with a default locale.  public GregorianCalendar (int year,int month,int dayofmonth,int hourofday, int minute) Constructs a gregoriancalendar with the given date and time settings for the default time zone with the default locale.  public GregorianCalendar (int year, int month,int dayofmonth,int hourofday,int minute,int second) Constructs a gregoriancalendar with the given date and time settings for the default time zone with the default locale.   Example:
private static String getDayOfWeek (int i) {
        switch (i) {
            case Calendar.SUNDAY:
                return "Sunday";
            case Calendar.MONDAY:
                return "Monday";
            case Calendar.TUESDAY:
                return "Tuesday";
            case Calendar.WEDNESDAY:
                return "Wednesday";
            case Calendar.THURSDAY:
                return "Thursday";
            case Calendar.FRIDAY:
                return "Friday";
            case Calendar.SATURDAY:
                return "Saturday";
            default:
                return "";
        }
    }

    public static void main (String [] args) {
        // Current time, set the GregorianCalendar environment to the time zone of China and the locale of China
        GregorianCalendar gregorianCalendar = new GregorianCalendar (TimeZone.getTimeZone ("GMT + 8"), Locale.CHINA);

        // Get the minimum number of days on the first day of the week and the first week of the year
        System.out.println ("The minimum number of days in the first week of the year:" + gregorianCalendar.getMinimalDaysInFirstWeek ());
        System.out.println ("The first day of the week is:" + getDayOfWeek (gregorianCalendar.getFirstDayOfWeek ()));

        // Even if the Chinese locale is set, the first day of the week obtained here is Sunday, so you need to set it manually
        gregorianCalendar.setFirstDayOfWeek (Calendar.MONDAY);
        System.out.println ("The first day of the week is:" + getDayOfWeek (gregorianCalendar.getFirstDayOfWeek ()));

        // Print each field
        System.out.println ("BC or after AD:" + (gregorianCalendar.get (Calendar.ERA) == GregorianCalendar.BC? "BC":
                (gregorianCalendar.get (Calendar.ERA) == GregorianCalendar.AD? "AD": ""))));
        System.out.println ("Year:" + gregorianCalendar.get (Calendar.YEAR));

        // Month from 0-11
        System.out.println ("Month:" + (gregorianCalendar.get (Calendar.MONTH) + 1));

        System.out.println ("Week of the current year:" + gregorianCalendar.get (Calendar.WEEK_OF_YEAR));
        System.out.println ("Day of the current year:" + gregorianCalendar.get (Calendar.DAY_OF_YEAR));
        System.out.println ("Week of the current month:" + gregorianCalendar.get (Calendar.WEEK_OF_MONTH));

        // 1 to 7 always correspond to DAY_OF_WEEK_IN_MONTH 1; 8 to 14 always correspond to DAY_OF_WEEK_IN_MONTH 2 and so on
        // Negative numbers are calculated from the end, and the fixed week is 7 days
        System.out.println ("Week of the current month (fixed):" + gregorianCalendar.get (Calendar.DAY_OF_WEEK_IN_MONTH));

        System.out.println ("Day of the month:" + gregorianCalendar.get (Calendar.DATE));
        System.out.println ("Day of the month:" + gregorianCalendar.get (Calendar.DAY_OF_MONTH));
        System.out.println ("Week:" + getDayOfWeek (gregorianCalendar.get (Calendar.DAY_OF_WEEK)));
        System.out.println ("morning or afternoon:" + (gregorianCalendar.get (Calendar.AM_PM) == GregorianCalendar.AM? "Morning":
                (gregorianCalendar.get (Calendar.AM_PM) == GregorianCalendar.PM? "PM": "")));

        // Morning or afternoon hours. HOUR is used for the 12-hour clock (0-11). Noon and midnight are represented by 0 instead of 12.
        System.out.println ("Hour:" + gregorianCalendar.get (Calendar.HOUR));

        // Hour of the day. HOUR_OF_DAY is for a 24-hour clock.
        System.out.println ("Hour:" + gregorianCalendar.get (Calendar.HOUR_OF_DAY));

        System.out.println ("minutes:" + gregorianCalendar.get (Calendar.MINUTE));
        System.out.println ("Seconds:" + gregorianCalendar.get (Calendar.SECOND));
        System.out.println ("ms:" + gregorianCalendar.get (Calendar.MILLISECOND));

        // Indicate the approximate offset from GMT in milliseconds
        System.out.println ("Time zone offset:" + gregorianCalendar.get (Calendar.ZONE_OFFSET));

        // Indicates the offset of daylight saving time in milliseconds.
        System.out.println ("DST Offset:" + gregorianCalendar.get (Calendar.DST_OFFSET));
    }
Output:
Minimum number of days in the first week of the year: 1
The first day of the week is: Sunday
The first day of the week is: Monday
Before or after AD: AD
Year: 2016
Month: 7
Week of current year: 28
Day of the current year: 186
Week of current month: 2
Week of current month (fixed): 1
Day of the current month: 4
Day of the current month: 4
Week: Monday
Morning or afternoon: morning
Hours: 10
Hours: 10
Minutes: 50
Seconds: 13
Millisecond: 461
Time zone offset: 28800000
Daylight saving time offset: 0 

For other uses, refer to the JDK API help documentation.


Java.util.Date and Java.util.Calendar and related classes


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.