Path: blob/master/src/java.base/share/classes/java/util/Date.java
41152 views
/*1* Copyright (c) 1994, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.text.DateFormat;28import java.time.LocalDate;29import java.io.IOException;30import java.io.ObjectOutputStream;31import java.io.ObjectInputStream;32import java.lang.ref.SoftReference;33import java.time.Instant;34import sun.util.calendar.BaseCalendar;35import sun.util.calendar.CalendarDate;36import sun.util.calendar.CalendarSystem;37import sun.util.calendar.CalendarUtils;38import sun.util.calendar.Era;39import sun.util.calendar.Gregorian;40import sun.util.calendar.ZoneInfo;4142/**43* The class {@code Date} represents a specific instant44* in time, with millisecond precision.45* <p>46* Prior to JDK 1.1, the class {@code Date} had two additional47* functions. It allowed the interpretation of dates as year, month, day, hour,48* minute, and second values. It also allowed the formatting and parsing49* of date strings. Unfortunately, the API for these functions was not50* amenable to internationalization. As of JDK 1.1, the51* {@code Calendar} class should be used to convert between dates and time52* fields and the {@code DateFormat} class should be used to format and53* parse date strings.54* The corresponding methods in {@code Date} are deprecated.55* <p>56* Although the {@code Date} class is intended to reflect57* coordinated universal time (UTC), it may not do so exactly,58* depending on the host environment of the Java Virtual Machine.59* Nearly all modern operating systems assume that 1 day =60* 24 × 60 × 60 = 86400 seconds61* in all cases. In UTC, however, about once every year or two there62* is an extra second, called a "leap second." The leap63* second is always added as the last second of the day, and always64* on December 31 or June 30. For example, the last minute of the65* year 1995 was 61 seconds long, thanks to an added leap second.66* Most computer clocks are not accurate enough to be able to reflect67* the leap-second distinction.68* <p>69* Some computer standards are defined in terms of Greenwich mean70* time (GMT), which is equivalent to universal time (UT). GMT is71* the "civil" name for the standard; UT is the72* "scientific" name for the same standard. The73* distinction between UTC and UT is that UTC is based on an atomic74* clock and UT is based on astronomical observations, which for all75* practical purposes is an invisibly fine hair to split. Because the76* earth's rotation is not uniform (it slows down and speeds up77* in complicated ways), UT does not always flow uniformly. Leap78* seconds are introduced as needed into UTC so as to keep UTC within79* 0.9 seconds of UT1, which is a version of UT with certain80* corrections applied. There are other time and date systems as81* well; for example, the time scale used by the satellite-based82* global positioning system (GPS) is synchronized to UTC but is83* <i>not</i> adjusted for leap seconds. An interesting source of84* further information is the United States Naval Observatory (USNO):85* <blockquote><pre>86* <a href="https://www.usno.navy.mil/USNO">https://www.usno.navy.mil/USNO</a>87* </pre></blockquote>88* <p>89* and the material regarding "Systems of Time" at:90* <blockquote><pre>91* <a href="https://www.usno.navy.mil/USNO/time/master-clock/systems-of-time">https://www.usno.navy.mil/USNO/time/master-clock/systems-of-time</a>92* </pre></blockquote>93* <p>94* which has descriptions of various different time systems including95* UT, UT1, and UTC.96* <p>97* In all methods of class {@code Date} that accept or return98* year, month, date, hours, minutes, and seconds values, the99* following representations are used:100* <ul>101* <li>A year <i>y</i> is represented by the integer102* <i>y</i> {@code - 1900}.103* <li>A month is represented by an integer from 0 to 11; 0 is January,104* 1 is February, and so forth; thus 11 is December.105* <li>A date (day of month) is represented by an integer from 1 to 31106* in the usual manner.107* <li>An hour is represented by an integer from 0 to 23. Thus, the hour108* from midnight to 1 a.m. is hour 0, and the hour from noon to 1109* p.m. is hour 12.110* <li>A minute is represented by an integer from 0 to 59 in the usual manner.111* <li>A second is represented by an integer from 0 to 61; the values 60 and112* 61 occur only for leap seconds and even then only in Java113* implementations that actually track leap seconds correctly. Because114* of the manner in which leap seconds are currently introduced, it is115* extremely unlikely that two leap seconds will occur in the same116* minute, but this specification follows the date and time conventions117* for ISO C.118* </ul>119* <p>120* In all cases, arguments given to methods for these purposes need121* not fall within the indicated ranges; for example, a date may be122* specified as January 32 and is interpreted as meaning February 1.123*124* @author James Gosling125* @author Arthur van Hoff126* @author Alan Liu127* @see java.text.DateFormat128* @see java.util.Calendar129* @see java.util.TimeZone130* @since 1.0131*/132public class Date133implements java.io.Serializable, Cloneable, Comparable<Date>134{135private static final BaseCalendar gcal =136CalendarSystem.getGregorianCalendar();137private static BaseCalendar jcal;138139private transient long fastTime;140141/*142* If cdate is null, then fastTime indicates the time in millis.143* If cdate.isNormalized() is true, then fastTime and cdate are in144* synch. Otherwise, fastTime is ignored, and cdate indicates the145* time.146*/147private transient BaseCalendar.Date cdate;148149// Initialized just before the value is used. See parse().150private static int defaultCenturyStart;151152/* use serialVersionUID from modified java.util.Date for153* interoperability with JDK1.1. The Date was modified to write154* and read only the UTC time.155*/156@java.io.Serial157private static final long serialVersionUID = 7523967970034938905L;158159/**160* Allocates a {@code Date} object and initializes it so that161* it represents the time at which it was allocated, measured to the162* nearest millisecond.163*164* @see java.lang.System#currentTimeMillis()165*/166public Date() {167this(System.currentTimeMillis());168}169170/**171* Allocates a {@code Date} object and initializes it to172* represent the specified number of milliseconds since the173* standard base time known as "the epoch", namely January 1,174* 1970, 00:00:00 GMT.175*176* @param date the milliseconds since January 1, 1970, 00:00:00 GMT.177* @see java.lang.System#currentTimeMillis()178*/179public Date(long date) {180fastTime = date;181}182183/**184* Allocates a {@code Date} object and initializes it so that185* it represents midnight, local time, at the beginning of the day186* specified by the {@code year}, {@code month}, and187* {@code date} arguments.188*189* @param year the year minus 1900.190* @param month the month between 0-11.191* @param date the day of the month between 1-31.192* @see java.util.Calendar193* @deprecated As of JDK version 1.1,194* replaced by {@code Calendar.set(year + 1900, month, date)}195* or {@code GregorianCalendar(year + 1900, month, date)}.196*/197@Deprecated198public Date(int year, int month, int date) {199this(year, month, date, 0, 0, 0);200}201202/**203* Allocates a {@code Date} object and initializes it so that204* it represents the instant at the start of the minute specified by205* the {@code year}, {@code month}, {@code date},206* {@code hrs}, and {@code min} arguments, in the local207* time zone.208*209* @param year the year minus 1900.210* @param month the month between 0-11.211* @param date the day of the month between 1-31.212* @param hrs the hours between 0-23.213* @param min the minutes between 0-59.214* @see java.util.Calendar215* @deprecated As of JDK version 1.1,216* replaced by {@code Calendar.set(year + 1900, month, date, hrs, min)}217* or {@code GregorianCalendar(year + 1900, month, date, hrs, min)}.218*/219@Deprecated220public Date(int year, int month, int date, int hrs, int min) {221this(year, month, date, hrs, min, 0);222}223224/**225* Allocates a {@code Date} object and initializes it so that226* it represents the instant at the start of the second specified227* by the {@code year}, {@code month}, {@code date},228* {@code hrs}, {@code min}, and {@code sec} arguments,229* in the local time zone.230*231* @param year the year minus 1900.232* @param month the month between 0-11.233* @param date the day of the month between 1-31.234* @param hrs the hours between 0-23.235* @param min the minutes between 0-59.236* @param sec the seconds between 0-59.237* @see java.util.Calendar238* @deprecated As of JDK version 1.1,239* replaced by {@code Calendar.set(year + 1900, month, date, hrs, min, sec)}240* or {@code GregorianCalendar(year + 1900, month, date, hrs, min, sec)}.241*/242@Deprecated243public Date(int year, int month, int date, int hrs, int min, int sec) {244int y = year + 1900;245// month is 0-based. So we have to normalize month to support Long.MAX_VALUE.246if (month >= 12) {247y += month / 12;248month %= 12;249} else if (month < 0) {250y += CalendarUtils.floorDivide(month, 12);251month = CalendarUtils.mod(month, 12);252}253BaseCalendar cal = getCalendarSystem(y);254cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());255cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);256getTimeImpl();257cdate = null;258}259260/**261* Allocates a {@code Date} object and initializes it so that262* it represents the date and time indicated by the string263* {@code s}, which is interpreted as if by the264* {@link Date#parse} method.265*266* @param s a string representation of the date.267* @see java.text.DateFormat268* @see java.util.Date#parse(java.lang.String)269* @deprecated As of JDK version 1.1,270* replaced by {@code DateFormat.parse(String s)}.271*/272@Deprecated273public Date(String s) {274this(parse(s));275}276277/**278* Return a copy of this object.279*/280public Object clone() {281Date d = null;282try {283d = (Date)super.clone();284if (cdate != null) {285d.cdate = (BaseCalendar.Date) cdate.clone();286}287} catch (CloneNotSupportedException e) {} // Won't happen288return d;289}290291/**292* Determines the date and time based on the arguments. The293* arguments are interpreted as a year, month, day of the month,294* hour of the day, minute within the hour, and second within the295* minute, exactly as for the {@code Date} constructor with six296* arguments, except that the arguments are interpreted relative297* to UTC rather than to the local time zone. The time indicated is298* returned represented as the distance, measured in milliseconds,299* of that time from the epoch (00:00:00 GMT on January 1, 1970).300*301* @param year the year minus 1900.302* @param month the month between 0-11.303* @param date the day of the month between 1-31.304* @param hrs the hours between 0-23.305* @param min the minutes between 0-59.306* @param sec the seconds between 0-59.307* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT for308* the date and time specified by the arguments.309* @see java.util.Calendar310* @deprecated As of JDK version 1.1,311* replaced by {@code Calendar.set(year + 1900, month, date, hrs, min, sec)}312* or {@code GregorianCalendar(year + 1900, month, date, hrs, min, sec)}, using a UTC313* {@code TimeZone}, followed by {@code Calendar.getTime().getTime()}.314*/315@Deprecated316public static long UTC(int year, int month, int date,317int hrs, int min, int sec) {318int y = year + 1900;319// month is 0-based. So we have to normalize month to support Long.MAX_VALUE.320if (month >= 12) {321y += month / 12;322month %= 12;323} else if (month < 0) {324y += CalendarUtils.floorDivide(month, 12);325month = CalendarUtils.mod(month, 12);326}327int m = month + 1;328BaseCalendar cal = getCalendarSystem(y);329BaseCalendar.Date udate = (BaseCalendar.Date) cal.newCalendarDate(null);330udate.setNormalizedDate(y, m, date).setTimeOfDay(hrs, min, sec, 0);331332// Use a Date instance to perform normalization. Its fastTime333// is the UTC value after the normalization.334Date d = new Date(0);335d.normalize(udate);336return d.fastTime;337}338339/**340* Attempts to interpret the string {@code s} as a representation341* of a date and time. If the attempt is successful, the time342* indicated is returned represented as the distance, measured in343* milliseconds, of that time from the epoch (00:00:00 GMT on344* January 1, 1970). If the attempt fails, an345* {@code IllegalArgumentException} is thrown.346* <p>347* It accepts many syntaxes; in particular, it recognizes the IETF348* standard date syntax: "Sat, 12 Aug 1995 13:30:00 GMT". It also349* understands the continental U.S. time-zone abbreviations, but for350* general use, a time-zone offset should be used: "Sat, 12 Aug 1995351* 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich352* meridian). If no time zone is specified, the local time zone is353* assumed. GMT and UTC are considered equivalent.354* <p>355* The string {@code s} is processed from left to right, looking for356* data of interest. Any material in {@code s} that is within the357* ASCII parenthesis characters {@code (} and {@code )} is ignored.358* Parentheses may be nested. Otherwise, the only characters permitted359* within {@code s} are these ASCII characters:360* <blockquote><pre>361* abcdefghijklmnopqrstuvwxyz362* ABCDEFGHIJKLMNOPQRSTUVWXYZ363* 0123456789,+-:/</pre></blockquote>364* and whitespace characters.<p>365* A consecutive sequence of decimal digits is treated as a decimal366* number:<ul>367* <li>If a number is preceded by {@code +} or {@code -} and a year368* has already been recognized, then the number is a time-zone369* offset. If the number is less than 24, it is an offset measured370* in hours. Otherwise, it is regarded as an offset in minutes,371* expressed in 24-hour time format without punctuation. A372* preceding {@code -} means a westward offset. Time zone offsets373* are always relative to UTC (Greenwich). Thus, for example,374* {@code -5} occurring in the string would mean "five hours west375* of Greenwich" and {@code +0430} would mean "four hours and376* thirty minutes east of Greenwich." It is permitted for the377* string to specify {@code GMT}, {@code UT}, or {@code UTC}378* redundantly-for example, {@code GMT-5} or {@code utc+0430}.379* <li>The number is regarded as a year number if one of the380* following conditions is true:381* <ul>382* <li>The number is equal to or greater than 70 and followed by a383* space, comma, slash, or end of string384* <li>The number is less than 70, and both a month and a day of385* the month have already been recognized</li>386* </ul>387* If the recognized year number is less than 100, it is388* interpreted as an abbreviated year relative to a century of389* which dates are within 80 years before and 19 years after390* the time when the Date class is initialized.391* After adjusting the year number, 1900 is subtracted from392* it. For example, if the current year is 1999 then years in393* the range 19 to 99 are assumed to mean 1919 to 1999, while394* years from 0 to 18 are assumed to mean 2000 to 2018. Note395* that this is slightly different from the interpretation of396* years less than 100 that is used in {@link java.text.SimpleDateFormat}.397* <li>If the number is followed by a colon, it is regarded as an hour,398* unless an hour has already been recognized, in which case it is399* regarded as a minute.400* <li>If the number is followed by a slash, it is regarded as a month401* (it is decreased by 1 to produce a number in the range {@code 0}402* to {@code 11}), unless a month has already been recognized, in403* which case it is regarded as a day of the month.404* <li>If the number is followed by whitespace, a comma, a hyphen, or405* end of string, then if an hour has been recognized but not a406* minute, it is regarded as a minute; otherwise, if a minute has407* been recognized but not a second, it is regarded as a second;408* otherwise, it is regarded as a day of the month. </ul><p>409* A consecutive sequence of letters is regarded as a word and treated410* as follows:<ul>411* <li>A word that matches {@code AM}, ignoring case, is ignored (but412* the parse fails if an hour has not been recognized or is less413* than {@code 1} or greater than {@code 12}).414* <li>A word that matches {@code PM}, ignoring case, adds {@code 12}415* to the hour (but the parse fails if an hour has not been416* recognized or is less than {@code 1} or greater than {@code 12}).417* <li>Any word that matches any prefix of {@code SUNDAY, MONDAY, TUESDAY,418* WEDNESDAY, THURSDAY, FRIDAY}, or {@code SATURDAY}, ignoring419* case, is ignored. For example, {@code sat, Friday, TUE}, and420* {@code Thurs} are ignored.421* <li>Otherwise, any word that matches any prefix of {@code JANUARY,422* FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,423* OCTOBER, NOVEMBER}, or {@code DECEMBER}, ignoring case, and424* considering them in the order given here, is recognized as425* specifying a month and is converted to a number ({@code 0} to426* {@code 11}). For example, {@code aug, Sept, april}, and427* {@code NOV} are recognized as months. So is {@code Ma}, which428* is recognized as {@code MARCH}, not {@code MAY}.429* <li>Any word that matches {@code GMT, UT}, or {@code UTC}, ignoring430* case, is treated as referring to UTC.431* <li>Any word that matches {@code EST, CST, MST}, or {@code PST},432* ignoring case, is recognized as referring to the time zone in433* North America that is five, six, seven, or eight hours west of434* Greenwich, respectively. Any word that matches {@code EDT, CDT,435* MDT}, or {@code PDT}, ignoring case, is recognized as436* referring to the same time zone, respectively, during daylight437* saving time.</ul><p>438* Once the entire string s has been scanned, it is converted to a time439* result in one of two ways. If a time zone or time-zone offset has been440* recognized, then the year, month, day of month, hour, minute, and441* second are interpreted in UTC and then the time-zone offset is442* applied. Otherwise, the year, month, day of month, hour, minute, and443* second are interpreted in the local time zone.444*445* @param s a string to be parsed as a date.446* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT447* represented by the string argument.448* @see java.text.DateFormat449* @deprecated As of JDK version 1.1,450* replaced by {@code DateFormat.parse(String s)}.451*/452@Deprecated453public static long parse(String s) {454int year = Integer.MIN_VALUE;455int mon = -1;456int mday = -1;457int hour = -1;458int min = -1;459int sec = -1;460int millis = -1;461int c = -1;462int i = 0;463int n = -1;464int wst = -1;465int tzoffset = -1;466int prevc = 0;467syntax:468{469if (s == null)470break syntax;471int limit = s.length();472while (i < limit) {473c = s.charAt(i);474i++;475if (c <= ' ' || c == ',')476continue;477if (c == '(') { // skip comments478int depth = 1;479while (i < limit) {480c = s.charAt(i);481i++;482if (c == '(') depth++;483else if (c == ')')484if (--depth <= 0)485break;486}487continue;488}489if ('0' <= c && c <= '9') {490n = c - '0';491while (i < limit && '0' <= (c = s.charAt(i)) && c <= '9') {492n = n * 10 + c - '0';493i++;494}495if (prevc == '+' || prevc == '-' && year != Integer.MIN_VALUE) {496// timezone offset497if (n < 24)498n = n * 60; // EG. "GMT-3"499else500n = n % 100 + n / 100 * 60; // eg "GMT-0430"501if (prevc == '+') // plus means east of GMT502n = -n;503if (tzoffset != 0 && tzoffset != -1)504break syntax;505tzoffset = n;506} else if (n >= 70)507if (year != Integer.MIN_VALUE)508break syntax;509else if (c <= ' ' || c == ',' || c == '/' || i >= limit)510// year = n < 1900 ? n : n - 1900;511year = n;512else513break syntax;514else if (c == ':')515if (hour < 0)516hour = (byte) n;517else if (min < 0)518min = (byte) n;519else520break syntax;521else if (c == '/')522if (mon < 0)523mon = (byte) (n - 1);524else if (mday < 0)525mday = (byte) n;526else527break syntax;528else if (i < limit && c != ',' && c > ' ' && c != '-')529break syntax;530else if (hour >= 0 && min < 0)531min = (byte) n;532else if (min >= 0 && sec < 0)533sec = (byte) n;534else if (mday < 0)535mday = (byte) n;536// Handle two-digit years < 70 (70-99 handled above).537else if (year == Integer.MIN_VALUE && mon >= 0 && mday >= 0)538year = n;539else540break syntax;541prevc = 0;542} else if (c == '/' || c == ':' || c == '+' || c == '-')543prevc = c;544else {545int st = i - 1;546while (i < limit) {547c = s.charAt(i);548if (!('A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'))549break;550i++;551}552if (i <= st + 1)553break syntax;554int k;555for (k = wtb.length; --k >= 0;)556if (wtb[k].regionMatches(true, 0, s, st, i - st)) {557int action = ttb[k];558if (action != 0) {559if (action == 1) { // pm560if (hour > 12 || hour < 1)561break syntax;562else if (hour < 12)563hour += 12;564} else if (action == 14) { // am565if (hour > 12 || hour < 1)566break syntax;567else if (hour == 12)568hour = 0;569} else if (action <= 13) { // month!570if (mon < 0)571mon = (byte) (action - 2);572else573break syntax;574} else {575tzoffset = action - 10000;576}577}578break;579}580if (k < 0)581break syntax;582prevc = 0;583}584}585if (year == Integer.MIN_VALUE || mon < 0 || mday < 0)586break syntax;587// Parse 2-digit years within the correct default century.588if (year < 100) {589synchronized (Date.class) {590if (defaultCenturyStart == 0) {591defaultCenturyStart = gcal.getCalendarDate().getYear() - 80;592}593}594year += (defaultCenturyStart / 100) * 100;595if (year < defaultCenturyStart) year += 100;596}597if (sec < 0)598sec = 0;599if (min < 0)600min = 0;601if (hour < 0)602hour = 0;603BaseCalendar cal = getCalendarSystem(year);604if (tzoffset == -1) { // no time zone specified, have to use local605BaseCalendar.Date ldate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());606ldate.setDate(year, mon + 1, mday);607ldate.setTimeOfDay(hour, min, sec, 0);608return cal.getTime(ldate);609}610BaseCalendar.Date udate = (BaseCalendar.Date) cal.newCalendarDate(null); // no time zone611udate.setDate(year, mon + 1, mday);612udate.setTimeOfDay(hour, min, sec, 0);613return cal.getTime(udate) + tzoffset * (60 * 1000);614}615// syntax error616throw new IllegalArgumentException();617}618private static final String wtb[] = {619"am", "pm",620"monday", "tuesday", "wednesday", "thursday", "friday",621"saturday", "sunday",622"january", "february", "march", "april", "may", "june",623"july", "august", "september", "october", "november", "december",624"gmt", "ut", "utc", "est", "edt", "cst", "cdt",625"mst", "mdt", "pst", "pdt"626};627private static final int ttb[] = {62814, 1, 0, 0, 0, 0, 0, 0, 0,6292, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,63010000 + 0, 10000 + 0, 10000 + 0, // GMT/UT/UTC63110000 + 5 * 60, 10000 + 4 * 60, // EST/EDT63210000 + 6 * 60, 10000 + 5 * 60, // CST/CDT63310000 + 7 * 60, 10000 + 6 * 60, // MST/MDT63410000 + 8 * 60, 10000 + 7 * 60 // PST/PDT635};636637/**638* Returns a value that is the result of subtracting 1900 from the639* year that contains or begins with the instant in time represented640* by this {@code Date} object, as interpreted in the local641* time zone.642*643* @return the year represented by this date, minus 1900.644* @see java.util.Calendar645* @deprecated As of JDK version 1.1,646* replaced by {@code Calendar.get(Calendar.YEAR) - 1900}.647*/648@Deprecated649public int getYear() {650return normalize().getYear() - 1900;651}652653/**654* Sets the year of this {@code Date} object to be the specified655* value plus 1900. This {@code Date} object is modified so656* that it represents a point in time within the specified year,657* with the month, date, hour, minute, and second the same as658* before, as interpreted in the local time zone. (Of course, if659* the date was February 29, for example, and the year is set to a660* non-leap year, then the new date will be treated as if it were661* on March 1.)662*663* @param year the year value.664* @see java.util.Calendar665* @deprecated As of JDK version 1.1,666* replaced by {@code Calendar.set(Calendar.YEAR, year + 1900)}.667*/668@Deprecated669public void setYear(int year) {670getCalendarDate().setNormalizedYear(year + 1900);671}672673/**674* Returns a number representing the month that contains or begins675* with the instant in time represented by this {@code Date} object.676* The value returned is between {@code 0} and {@code 11},677* with the value {@code 0} representing January.678*679* @return the month represented by this date.680* @see java.util.Calendar681* @deprecated As of JDK version 1.1,682* replaced by {@code Calendar.get(Calendar.MONTH)}.683*/684@Deprecated685public int getMonth() {686return normalize().getMonth() - 1; // adjust 1-based to 0-based687}688689/**690* Sets the month of this date to the specified value. This691* {@code Date} object is modified so that it represents a point692* in time within the specified month, with the year, date, hour,693* minute, and second the same as before, as interpreted in the694* local time zone. If the date was October 31, for example, and695* the month is set to June, then the new date will be treated as696* if it were on July 1, because June has only 30 days.697*698* @param month the month value between 0-11.699* @see java.util.Calendar700* @deprecated As of JDK version 1.1,701* replaced by {@code Calendar.set(Calendar.MONTH, int month)}.702*/703@Deprecated704public void setMonth(int month) {705int y = 0;706if (month >= 12) {707y = month / 12;708month %= 12;709} else if (month < 0) {710y = CalendarUtils.floorDivide(month, 12);711month = CalendarUtils.mod(month, 12);712}713BaseCalendar.Date d = getCalendarDate();714if (y != 0) {715d.setNormalizedYear(d.getNormalizedYear() + y);716}717d.setMonth(month + 1); // adjust 0-based to 1-based month numbering718}719720/**721* Returns the day of the month represented by this {@code Date} object.722* The value returned is between {@code 1} and {@code 31}723* representing the day of the month that contains or begins with the724* instant in time represented by this {@code Date} object, as725* interpreted in the local time zone.726*727* @return the day of the month represented by this date.728* @see java.util.Calendar729* @deprecated As of JDK version 1.1,730* replaced by {@code Calendar.get(Calendar.DAY_OF_MONTH)}.731*/732@Deprecated733public int getDate() {734return normalize().getDayOfMonth();735}736737/**738* Sets the day of the month of this {@code Date} object to the739* specified value. This {@code Date} object is modified so that740* it represents a point in time within the specified day of the741* month, with the year, month, hour, minute, and second the same742* as before, as interpreted in the local time zone. If the date743* was April 30, for example, and the date is set to 31, then it744* will be treated as if it were on May 1, because April has only745* 30 days.746*747* @param date the day of the month value between 1-31.748* @see java.util.Calendar749* @deprecated As of JDK version 1.1,750* replaced by {@code Calendar.set(Calendar.DAY_OF_MONTH, int date)}.751*/752@Deprecated753public void setDate(int date) {754getCalendarDate().setDayOfMonth(date);755}756757/**758* Returns the day of the week represented by this date. The759* returned value ({@code 0} = Sunday, {@code 1} = Monday,760* {@code 2} = Tuesday, {@code 3} = Wednesday, {@code 4} =761* Thursday, {@code 5} = Friday, {@code 6} = Saturday)762* represents the day of the week that contains or begins with763* the instant in time represented by this {@code Date} object,764* as interpreted in the local time zone.765*766* @return the day of the week represented by this date.767* @see java.util.Calendar768* @deprecated As of JDK version 1.1,769* replaced by {@code Calendar.get(Calendar.DAY_OF_WEEK)}.770*/771@Deprecated772public int getDay() {773return normalize().getDayOfWeek() - BaseCalendar.SUNDAY;774}775776/**777* Returns the hour represented by this {@code Date} object. The778* returned value is a number ({@code 0} through {@code 23})779* representing the hour within the day that contains or begins780* with the instant in time represented by this {@code Date}781* object, as interpreted in the local time zone.782*783* @return the hour represented by this date.784* @see java.util.Calendar785* @deprecated As of JDK version 1.1,786* replaced by {@code Calendar.get(Calendar.HOUR_OF_DAY)}.787*/788@Deprecated789public int getHours() {790return normalize().getHours();791}792793/**794* Sets the hour of this {@code Date} object to the specified value.795* This {@code Date} object is modified so that it represents a point796* in time within the specified hour of the day, with the year, month,797* date, minute, and second the same as before, as interpreted in the798* local time zone.799*800* @param hours the hour value.801* @see java.util.Calendar802* @deprecated As of JDK version 1.1,803* replaced by {@code Calendar.set(Calendar.HOUR_OF_DAY, int hours)}.804*/805@Deprecated806public void setHours(int hours) {807getCalendarDate().setHours(hours);808}809810/**811* Returns the number of minutes past the hour represented by this date,812* as interpreted in the local time zone.813* The value returned is between {@code 0} and {@code 59}.814*815* @return the number of minutes past the hour represented by this date.816* @see java.util.Calendar817* @deprecated As of JDK version 1.1,818* replaced by {@code Calendar.get(Calendar.MINUTE)}.819*/820@Deprecated821public int getMinutes() {822return normalize().getMinutes();823}824825/**826* Sets the minutes of this {@code Date} object to the specified value.827* This {@code Date} object is modified so that it represents a point828* in time within the specified minute of the hour, with the year, month,829* date, hour, and second the same as before, as interpreted in the830* local time zone.831*832* @param minutes the value of the minutes.833* @see java.util.Calendar834* @deprecated As of JDK version 1.1,835* replaced by {@code Calendar.set(Calendar.MINUTE, int minutes)}.836*/837@Deprecated838public void setMinutes(int minutes) {839getCalendarDate().setMinutes(minutes);840}841842/**843* Returns the number of seconds past the minute represented by this date.844* The value returned is between {@code 0} and {@code 61}. The845* values {@code 60} and {@code 61} can only occur on those846* Java Virtual Machines that take leap seconds into account.847*848* @return the number of seconds past the minute represented by this date.849* @see java.util.Calendar850* @deprecated As of JDK version 1.1,851* replaced by {@code Calendar.get(Calendar.SECOND)}.852*/853@Deprecated854public int getSeconds() {855return normalize().getSeconds();856}857858/**859* Sets the seconds of this {@code Date} to the specified value.860* This {@code Date} object is modified so that it represents a861* point in time within the specified second of the minute, with862* the year, month, date, hour, and minute the same as before, as863* interpreted in the local time zone.864*865* @param seconds the seconds value.866* @see java.util.Calendar867* @deprecated As of JDK version 1.1,868* replaced by {@code Calendar.set(Calendar.SECOND, int seconds)}.869*/870@Deprecated871public void setSeconds(int seconds) {872getCalendarDate().setSeconds(seconds);873}874875/**876* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT877* represented by this {@code Date} object.878*879* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT880* represented by this date.881*/882public long getTime() {883return getTimeImpl();884}885886private final long getTimeImpl() {887if (cdate != null && !cdate.isNormalized()) {888normalize();889}890return fastTime;891}892893/**894* Sets this {@code Date} object to represent a point in time that is895* {@code time} milliseconds after January 1, 1970 00:00:00 GMT.896*897* @param time the number of milliseconds.898*/899public void setTime(long time) {900fastTime = time;901cdate = null;902}903904/**905* Tests if this date is before the specified date.906*907* @param when a date.908* @return {@code true} if and only if the instant of time909* represented by this {@code Date} object is strictly910* earlier than the instant represented by {@code when};911* {@code false} otherwise.912* @throws NullPointerException if {@code when} is null.913*/914public boolean before(Date when) {915return getMillisOf(this) < getMillisOf(when);916}917918/**919* Tests if this date is after the specified date.920*921* @param when a date.922* @return {@code true} if and only if the instant represented923* by this {@code Date} object is strictly later than the924* instant represented by {@code when};925* {@code false} otherwise.926* @throws NullPointerException if {@code when} is null.927*/928public boolean after(Date when) {929return getMillisOf(this) > getMillisOf(when);930}931932/**933* Compares two dates for equality.934* The result is {@code true} if and only if the argument is935* not {@code null} and is a {@code Date} object that936* represents the same point in time, to the millisecond, as this object.937* <p>938* Thus, two {@code Date} objects are equal if and only if the939* {@code getTime} method returns the same {@code long}940* value for both.941*942* @param obj the object to compare with.943* @return {@code true} if the objects are the same;944* {@code false} otherwise.945* @see java.util.Date#getTime()946*/947public boolean equals(Object obj) {948return obj instanceof Date && getTime() == ((Date) obj).getTime();949}950951/**952* Returns the millisecond value of this {@code Date} object953* without affecting its internal state.954*/955static final long getMillisOf(Date date) {956if (date.getClass() != Date.class) {957return date.getTime();958}959if (date.cdate == null || date.cdate.isNormalized()) {960return date.fastTime;961}962BaseCalendar.Date d = (BaseCalendar.Date) date.cdate.clone();963return gcal.getTime(d);964}965966/**967* Compares two Dates for ordering.968*969* @param anotherDate the {@code Date} to be compared.970* @return the value {@code 0} if the argument Date is equal to971* this Date; a value less than {@code 0} if this Date972* is before the Date argument; and a value greater than973* {@code 0} if this Date is after the Date argument.974* @since 1.2975* @throws NullPointerException if {@code anotherDate} is null.976*/977public int compareTo(Date anotherDate) {978long thisTime = getMillisOf(this);979long anotherTime = getMillisOf(anotherDate);980return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));981}982983/**984* Returns a hash code value for this object. The result is the985* exclusive OR of the two halves of the primitive {@code long}986* value returned by the {@link Date#getTime}987* method. That is, the hash code is the value of the expression:988* <blockquote><pre>{@code989* (int)(this.getTime()^(this.getTime() >>> 32))990* }</pre></blockquote>991*992* @return a hash code value for this object.993*/994public int hashCode() {995long ht = this.getTime();996return (int) ht ^ (int) (ht >> 32);997}998999/**1000* Converts this {@code Date} object to a {@code String}1001* of the form:1002* <blockquote><pre>1003* dow mon dd hh:mm:ss zzz yyyy</pre></blockquote>1004* where:<ul>1005* <li>{@code dow} is the day of the week ({@code Sun, Mon, Tue, Wed,1006* Thu, Fri, Sat}).1007* <li>{@code mon} is the month ({@code Jan, Feb, Mar, Apr, May, Jun,1008* Jul, Aug, Sep, Oct, Nov, Dec}).1009* <li>{@code dd} is the day of the month ({@code 01} through1010* {@code 31}), as two decimal digits.1011* <li>{@code hh} is the hour of the day ({@code 00} through1012* {@code 23}), as two decimal digits.1013* <li>{@code mm} is the minute within the hour ({@code 00} through1014* {@code 59}), as two decimal digits.1015* <li>{@code ss} is the second within the minute ({@code 00} through1016* {@code 61}, as two decimal digits.1017* <li>{@code zzz} is the time zone (and may reflect daylight saving1018* time). Standard time zone abbreviations include those1019* recognized by the method {@code parse}. If time zone1020* information is not available, then {@code zzz} is empty -1021* that is, it consists of no characters at all.1022* <li>{@code yyyy} is the year, as four decimal digits.1023* </ul>1024*1025* @return a string representation of this date.1026* @see java.util.Date#toLocaleString()1027* @see java.util.Date#toGMTString()1028*/1029public String toString() {1030// "EEE MMM dd HH:mm:ss zzz yyyy";1031BaseCalendar.Date date = normalize();1032StringBuilder sb = new StringBuilder(28);1033int index = date.getDayOfWeek();1034if (index == BaseCalendar.SUNDAY) {1035index = 8;1036}1037convertToAbbr(sb, wtb[index]).append(' '); // EEE1038convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM1039CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd10401041CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH1042CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm1043CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss1044TimeZone zi = date.getZone();1045if (zi != null) {1046sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz1047} else {1048sb.append("GMT");1049}1050sb.append(' ').append(date.getYear()); // yyyy1051return sb.toString();1052}10531054/**1055* Converts the given name to its 3-letter abbreviation (e.g.,1056* "monday" -> "Mon") and stored the abbreviation in the given1057* {@code StringBuilder}.1058*/1059private static final StringBuilder convertToAbbr(StringBuilder sb, String name) {1060sb.append(Character.toUpperCase(name.charAt(0)));1061sb.append(name.charAt(1)).append(name.charAt(2));1062return sb;1063}10641065/**1066* Creates a string representation of this {@code Date} object in an1067* implementation-dependent form. The intent is that the form should1068* be familiar to the user of the Java application, wherever it may1069* happen to be running. The intent is comparable to that of the1070* "{@code %c}" format supported by the {@code strftime()}1071* function of ISO C.1072*1073* @return a string representation of this date, using the locale1074* conventions.1075* @see java.text.DateFormat1076* @see java.util.Date#toString()1077* @see java.util.Date#toGMTString()1078* @deprecated As of JDK version 1.1,1079* replaced by {@code DateFormat.format(Date date)}.1080*/1081@Deprecated1082public String toLocaleString() {1083DateFormat formatter = DateFormat.getDateTimeInstance();1084return formatter.format(this);1085}10861087/**1088* Creates a string representation of this {@code Date} object of1089* the form:1090* <blockquote><pre>1091* d mon yyyy hh:mm:ss GMT</pre></blockquote>1092* where:<ul>1093* <li><i>d</i> is the day of the month ({@code 1} through {@code 31}),1094* as one or two decimal digits.1095* <li><i>mon</i> is the month ({@code Jan, Feb, Mar, Apr, May, Jun, Jul,1096* Aug, Sep, Oct, Nov, Dec}).1097* <li><i>yyyy</i> is the year, as four decimal digits.1098* <li><i>hh</i> is the hour of the day ({@code 00} through {@code 23}),1099* as two decimal digits.1100* <li><i>mm</i> is the minute within the hour ({@code 00} through1101* {@code 59}), as two decimal digits.1102* <li><i>ss</i> is the second within the minute ({@code 00} through1103* {@code 61}), as two decimal digits.1104* <li><i>GMT</i> is exactly the ASCII letters "{@code GMT}" to indicate1105* Greenwich Mean Time.1106* </ul><p>1107* The result does not depend on the local time zone.1108*1109* @return a string representation of this date, using the Internet GMT1110* conventions.1111* @see java.text.DateFormat1112* @see java.util.Date#toString()1113* @see java.util.Date#toLocaleString()1114* @deprecated As of JDK version 1.1,1115* replaced by {@code DateFormat.format(Date date)}, using a1116* GMT {@code TimeZone}.1117*/1118@Deprecated1119public String toGMTString() {1120// d MMM yyyy HH:mm:ss 'GMT'1121long t = getTime();1122BaseCalendar cal = getCalendarSystem(t);1123BaseCalendar.Date date =1124(BaseCalendar.Date) cal.getCalendarDate(getTime(), (TimeZone)null);1125StringBuilder sb = new StringBuilder(32);1126CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 1).append(' '); // d1127convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM1128sb.append(date.getYear()).append(' '); // yyyy1129CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH1130CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm1131CalendarUtils.sprintf0d(sb, date.getSeconds(), 2); // ss1132sb.append(" GMT"); // ' GMT'1133return sb.toString();1134}11351136/**1137* Returns the offset, measured in minutes, for the local time zone1138* relative to UTC that is appropriate for the time represented by1139* this {@code Date} object.1140* <p>1141* For example, in Massachusetts, five time zones west of Greenwich:1142* <blockquote><pre>1143* new Date(96, 1, 14).getTimezoneOffset() returns 300</pre></blockquote>1144* because on February 14, 1996, standard time (Eastern Standard Time)1145* is in use, which is offset five hours from UTC; but:1146* <blockquote><pre>1147* new Date(96, 5, 1).getTimezoneOffset() returns 240</pre></blockquote>1148* because on June 1, 1996, daylight saving time (Eastern Daylight Time)1149* is in use, which is offset only four hours from UTC.<p>1150* This method produces the same result as if it computed:1151* <blockquote><pre>1152* (this.getTime() - UTC(this.getYear(),1153* this.getMonth(),1154* this.getDate(),1155* this.getHours(),1156* this.getMinutes(),1157* this.getSeconds())) / (60 * 1000)1158* </pre></blockquote>1159*1160* @return the time-zone offset, in minutes, for the current time zone.1161* @see java.util.Calendar#ZONE_OFFSET1162* @see java.util.Calendar#DST_OFFSET1163* @see java.util.TimeZone#getDefault1164* @deprecated As of JDK version 1.1,1165* replaced by {@code -(Calendar.get(Calendar.ZONE_OFFSET) +1166* Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)}.1167*/1168@Deprecated1169public int getTimezoneOffset() {1170int zoneOffset;1171if (cdate == null) {1172TimeZone tz = TimeZone.getDefaultRef();1173if (tz instanceof ZoneInfo) {1174zoneOffset = ((ZoneInfo)tz).getOffsets(fastTime, null);1175} else {1176zoneOffset = tz.getOffset(fastTime);1177}1178} else {1179normalize();1180zoneOffset = cdate.getZoneOffset();1181}1182return -zoneOffset/60000; // convert to minutes1183}11841185private final BaseCalendar.Date getCalendarDate() {1186if (cdate == null) {1187BaseCalendar cal = getCalendarSystem(fastTime);1188cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime,1189TimeZone.getDefaultRef());1190}1191return cdate;1192}11931194private final BaseCalendar.Date normalize() {1195if (cdate == null) {1196BaseCalendar cal = getCalendarSystem(fastTime);1197cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime,1198TimeZone.getDefaultRef());1199return cdate;1200}12011202// Normalize cdate with the TimeZone in cdate first. This is1203// required for the compatible behavior.1204if (!cdate.isNormalized()) {1205cdate = normalize(cdate);1206}12071208// If the default TimeZone has changed, then recalculate the1209// fields with the new TimeZone.1210TimeZone tz = TimeZone.getDefaultRef();1211if (tz != cdate.getZone()) {1212cdate.setZone(tz);1213CalendarSystem cal = getCalendarSystem(cdate);1214cal.getCalendarDate(fastTime, cdate);1215}1216return cdate;1217}12181219// fastTime and the returned data are in sync upon return.1220private final BaseCalendar.Date normalize(BaseCalendar.Date date) {1221int y = date.getNormalizedYear();1222int m = date.getMonth();1223int d = date.getDayOfMonth();1224int hh = date.getHours();1225int mm = date.getMinutes();1226int ss = date.getSeconds();1227int ms = date.getMillis();1228TimeZone tz = date.getZone();12291230// If the specified year can't be handled using a long value1231// in milliseconds, GregorianCalendar is used for full1232// compatibility with underflow and overflow. This is required1233// by some JCK tests. The limits are based max year values -1234// years that can be represented by max values of d, hh, mm,1235// ss and ms. Also, let GregorianCalendar handle the default1236// cutover year so that we don't need to worry about the1237// transition here.1238if (y == 1582 || y > 280000000 || y < -280000000) {1239if (tz == null) {1240tz = TimeZone.getTimeZone("GMT");1241}1242GregorianCalendar gc = new GregorianCalendar(tz);1243gc.clear();1244gc.set(GregorianCalendar.MILLISECOND, ms);1245gc.set(y, m-1, d, hh, mm, ss);1246fastTime = gc.getTimeInMillis();1247BaseCalendar cal = getCalendarSystem(fastTime);1248date = (BaseCalendar.Date) cal.getCalendarDate(fastTime, tz);1249return date;1250}12511252BaseCalendar cal = getCalendarSystem(y);1253if (cal != getCalendarSystem(date)) {1254date = (BaseCalendar.Date) cal.newCalendarDate(tz);1255date.setNormalizedDate(y, m, d).setTimeOfDay(hh, mm, ss, ms);1256}1257// Perform the GregorianCalendar-style normalization.1258fastTime = cal.getTime(date);12591260// In case the normalized date requires the other calendar1261// system, we need to recalculate it using the other one.1262BaseCalendar ncal = getCalendarSystem(fastTime);1263if (ncal != cal) {1264date = (BaseCalendar.Date) ncal.newCalendarDate(tz);1265date.setNormalizedDate(y, m, d).setTimeOfDay(hh, mm, ss, ms);1266fastTime = ncal.getTime(date);1267}1268return date;1269}12701271/**1272* Returns the Gregorian or Julian calendar system to use with the1273* given date. Use Gregorian from October 15, 1582.1274*1275* @param year normalized calendar year (not -1900)1276* @return the CalendarSystem to use for the specified date1277*/1278private static final BaseCalendar getCalendarSystem(int year) {1279if (year >= 1582) {1280return gcal;1281}1282return getJulianCalendar();1283}12841285private static final BaseCalendar getCalendarSystem(long utc) {1286// Quickly check if the time stamp given by `utc' is the Epoch1287// or later. If it's before 1970, we convert the cutover to1288// local time to compare.1289if (utc >= 01290|| utc >= GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER1291- TimeZone.getDefaultRef().getOffset(utc)) {1292return gcal;1293}1294return getJulianCalendar();1295}12961297private static final BaseCalendar getCalendarSystem(BaseCalendar.Date cdate) {1298if (jcal == null) {1299return gcal;1300}1301if (cdate.getEra() != null) {1302return jcal;1303}1304return gcal;1305}13061307private static final synchronized BaseCalendar getJulianCalendar() {1308if (jcal == null) {1309jcal = (BaseCalendar) CalendarSystem.forName("julian");1310}1311return jcal;1312}13131314/**1315* Save the state of this object to a stream (i.e., serialize it).1316*1317* @serialData The value returned by {@code getTime()}1318* is emitted (long). This represents the offset from1319* January 1, 1970, 00:00:00 GMT in milliseconds.1320*/1321@java.io.Serial1322private void writeObject(ObjectOutputStream s)1323throws IOException1324{1325s.defaultWriteObject();1326s.writeLong(getTimeImpl());1327}13281329/**1330* Reconstitute this object from a stream (i.e., deserialize it).1331*/1332@java.io.Serial1333private void readObject(ObjectInputStream s)1334throws IOException, ClassNotFoundException1335{1336s.defaultReadObject();1337fastTime = s.readLong();1338}13391340/**1341* Obtains an instance of {@code Date} from an {@code Instant} object.1342* <p>1343* {@code Instant} uses a precision of nanoseconds, whereas {@code Date}1344* uses a precision of milliseconds. The conversion will truncate any1345* excess precision information as though the amount in nanoseconds was1346* subject to integer division by one million.1347* <p>1348* {@code Instant} can store points on the time-line further in the future1349* and further in the past than {@code Date}. In this scenario, this method1350* will throw an exception.1351*1352* @param instant the instant to convert1353* @return a {@code Date} representing the same point on the time-line as1354* the provided instant1355* @throws NullPointerException if {@code instant} is null.1356* @throws IllegalArgumentException if the instant is too large to1357* represent as a {@code Date}1358* @since 1.81359*/1360public static Date from(Instant instant) {1361try {1362return new Date(instant.toEpochMilli());1363} catch (ArithmeticException ex) {1364throw new IllegalArgumentException(ex);1365}1366}13671368/**1369* Converts this {@code Date} object to an {@code Instant}.1370* <p>1371* The conversion creates an {@code Instant} that represents the same1372* point on the time-line as this {@code Date}.1373*1374* @return an instant representing the same point on the time-line as1375* this {@code Date} object1376* @since 1.81377*/1378public Instant toInstant() {1379return Instant.ofEpochMilli(getTime());1380}1381}138213831384