Calendar.java 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  1. /* Calendar.java --
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006,
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import gnu.java.lang.CPStringBuilder;
  34. import java.io.IOException;
  35. import java.io.ObjectInputStream;
  36. import java.io.ObjectOutputStream;
  37. import java.io.Serializable;
  38. import java.lang.reflect.Constructor;
  39. import java.lang.reflect.InvocationTargetException;
  40. import java.text.DateFormatSymbols;
  41. /**
  42. * This class is an abstract base class for Calendars, which can be
  43. * used to convert between <code>Date</code> objects and a set of
  44. * integer fields which represent <code>YEAR</code>,
  45. * <code>MONTH</code>, <code>DAY</code>, etc. The <code>Date</code>
  46. * object represents a time in milliseconds since the Epoch. <br>
  47. *
  48. * This class is locale sensitive. To get the Object matching the
  49. * current locale you can use <code>getInstance</code>. You can even provide
  50. * a locale or a timezone. <code>getInstance</code> returns currently
  51. * a <code>GregorianCalendar</code> for the current date. <br>
  52. *
  53. * If you want to convert a date from the Year, Month, Day, DayOfWeek,
  54. * etc. Representation to a <code>Date</code>-Object, you can create
  55. * a new Calendar with <code>getInstance()</code>,
  56. * <code>clear()</code> all fields, <code>set(int,int)</code> the
  57. * fields you need and convert it with <code>getTime()</code>. <br>
  58. *
  59. * If you want to convert a <code>Date</code>-object to the Calendar
  60. * representation, create a new Calendar, assign the
  61. * <code>Date</code>-Object with <code>setTime()</code>, and read the
  62. * fields with <code>get(int)</code>. <br>
  63. *
  64. * When computing the date from time fields, it may happen, that there
  65. * are either two few fields set, or some fields are inconsistent. This
  66. * cases will handled in a calendar specific way. Missing fields are
  67. * replaced by the fields of the epoch: 1970 January 1 00:00. <br>
  68. *
  69. * To understand, how the day of year is computed out of the fields
  70. * look at the following table. It is traversed from top to bottom,
  71. * and for the first line all fields are set, that line is used to
  72. * compute the day. <br>
  73. *
  74. *
  75. <pre>month + day_of_month
  76. month + week_of_month + day_of_week
  77. month + day_of_week_of_month + day_of_week
  78. day_of_year
  79. day_of_week + week_of_year</pre>
  80. *
  81. * The hour_of_day-field takes precedence over the ampm and
  82. * hour_of_ampm fields. <br>
  83. *
  84. * <STRONG>Note:</STRONG> This can differ for non-Gregorian calendar. <br>
  85. *
  86. * To convert a calendar to a human readable form and vice versa, use
  87. * the <code>java.text.DateFormat</code> class. <br>
  88. *
  89. * Other useful things you can do with an calendar, is
  90. * <code>roll</code>ing fields (that means increase/decrease a
  91. * specific field by one, propagating overflows), or
  92. * <code>add</code>ing/substracting a fixed amount to a field.
  93. *
  94. * @author Aaron M. Renn (arenn@urbanophile.com)
  95. * @author Jochen Hoenicke (Jochen.Hoenicke@Informatik.Uni-Oldenburg.de)
  96. * @author Warren Levy (warrenl@cygnus.com)
  97. * @author Jeff Sturm (jsturm@one-point.com)
  98. * @author Tom Tromey (tromey@redhat.com)
  99. * @author Bryce McKinlay (mckinlay@redhat.com)
  100. * @author Ingo Proetel (proetel@aicas.com)
  101. * @author Jerry Quinn (jlquinn@optonline.net)
  102. * @author Jeroen Frijters (jeroen@frijters.net)
  103. * @author Noa Resare (noa@resare.com)
  104. * @author Sven de Marothy (sven@physto.se)
  105. * @author David Gilbert (david.gilbert@object-refinery.com)
  106. * @author Olivier Jolly (olivier.jolly@pcedev.com)
  107. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  108. * @see Date
  109. * @see GregorianCalendar
  110. * @see TimeZone
  111. * @see java.text.DateFormat
  112. */
  113. public abstract class Calendar
  114. implements Serializable, Cloneable, Comparable<Calendar>
  115. {
  116. /**
  117. * Constant representing the era time field.
  118. */
  119. public static final int ERA = 0;
  120. /**
  121. * Constant representing the year time field.
  122. */
  123. public static final int YEAR = 1;
  124. /**
  125. * Constant representing the month time field. This field
  126. * should contain one of the JANUARY,...,DECEMBER constants below.
  127. */
  128. public static final int MONTH = 2;
  129. /**
  130. * Constant representing the week of the year field.
  131. * @see #setFirstDayOfWeek(int)
  132. */
  133. public static final int WEEK_OF_YEAR = 3;
  134. /**
  135. * Constant representing the week of the month time field.
  136. * @see #setFirstDayOfWeek(int)
  137. */
  138. public static final int WEEK_OF_MONTH = 4;
  139. /**
  140. * Constant representing the day time field, synonym for DAY_OF_MONTH.
  141. */
  142. public static final int DATE = 5;
  143. /**
  144. * Constant representing the day time field.
  145. */
  146. public static final int DAY_OF_MONTH = 5;
  147. /**
  148. * Constant representing the day of year time field. This is
  149. * 1 for the first day in month.
  150. */
  151. public static final int DAY_OF_YEAR = 6;
  152. /**
  153. * Constant representing the day of week time field. This field
  154. * should contain one of the SUNDAY,...,SATURDAY constants below.
  155. */
  156. public static final int DAY_OF_WEEK = 7;
  157. /**
  158. * Constant representing the day-of-week-in-month field. For
  159. * instance this field contains 2 for the second thursday in a
  160. * month. If you give a negative number here, the day will count
  161. * from the end of the month.
  162. */
  163. public static final int DAY_OF_WEEK_IN_MONTH = 8;
  164. /**
  165. * Constant representing the part of the day for 12-hour clock. This
  166. * should be one of AM or PM.
  167. */
  168. public static final int AM_PM = 9;
  169. /**
  170. * Constant representing the hour time field for 12-hour clock.
  171. */
  172. public static final int HOUR = 10;
  173. /**
  174. * Constant representing the hour of day time field for 24-hour clock.
  175. */
  176. public static final int HOUR_OF_DAY = 11;
  177. /**
  178. * Constant representing the minute of hour time field.
  179. */
  180. public static final int MINUTE = 12;
  181. /**
  182. * Constant representing the second time field.
  183. */
  184. public static final int SECOND = 13;
  185. /**
  186. * Constant representing the millisecond time field.
  187. */
  188. public static final int MILLISECOND = 14;
  189. /**
  190. * Constant representing the time zone offset time field for the
  191. * time given in the other fields. It is measured in
  192. * milliseconds. The default is the offset of the time zone.
  193. */
  194. public static final int ZONE_OFFSET = 15;
  195. /**
  196. * Constant representing the daylight saving time offset in
  197. * milliseconds. The default is the value given by the time zone.
  198. */
  199. public static final int DST_OFFSET = 16;
  200. /**
  201. * Number of time fields.
  202. */
  203. public static final int FIELD_COUNT = 17;
  204. /**
  205. * Constant representing Sunday.
  206. */
  207. public static final int SUNDAY = 1;
  208. /**
  209. * Constant representing Monday.
  210. */
  211. public static final int MONDAY = 2;
  212. /**
  213. * Constant representing Tuesday.
  214. */
  215. public static final int TUESDAY = 3;
  216. /**
  217. * Constant representing Wednesday.
  218. */
  219. public static final int WEDNESDAY = 4;
  220. /**
  221. * Constant representing Thursday.
  222. */
  223. public static final int THURSDAY = 5;
  224. /**
  225. * Constant representing Friday.
  226. */
  227. public static final int FRIDAY = 6;
  228. /**
  229. * Constant representing Saturday.
  230. */
  231. public static final int SATURDAY = 7;
  232. /**
  233. * Constant representing January.
  234. */
  235. public static final int JANUARY = 0;
  236. /**
  237. * Constant representing February.
  238. */
  239. public static final int FEBRUARY = 1;
  240. /**
  241. * Constant representing March.
  242. */
  243. public static final int MARCH = 2;
  244. /**
  245. * Constant representing April.
  246. */
  247. public static final int APRIL = 3;
  248. /**
  249. * Constant representing May.
  250. */
  251. public static final int MAY = 4;
  252. /**
  253. * Constant representing June.
  254. */
  255. public static final int JUNE = 5;
  256. /**
  257. * Constant representing July.
  258. */
  259. public static final int JULY = 6;
  260. /**
  261. * Constant representing August.
  262. */
  263. public static final int AUGUST = 7;
  264. /**
  265. * Constant representing September.
  266. */
  267. public static final int SEPTEMBER = 8;
  268. /**
  269. * Constant representing October.
  270. */
  271. public static final int OCTOBER = 9;
  272. /**
  273. * Constant representing November.
  274. */
  275. public static final int NOVEMBER = 10;
  276. /**
  277. * Constant representing December.
  278. */
  279. public static final int DECEMBER = 11;
  280. /**
  281. * Constant representing Undecimber. This is an artificial name useful
  282. * for lunar calendars.
  283. */
  284. public static final int UNDECIMBER = 12;
  285. /**
  286. * Useful constant for 12-hour clock.
  287. */
  288. public static final int AM = 0;
  289. /**
  290. * Useful constant for 12-hour clock.
  291. */
  292. public static final int PM = 1;
  293. /**
  294. * A style specifier for {@link #getDisplayNames(int,int,Locale)}
  295. * stating that names should be returned in both long and short variants.
  296. *
  297. * @since 1.6
  298. * @see #SHORT
  299. * @see #LONG
  300. */
  301. public static final int ALL_STYLES = 0;
  302. /**
  303. * A style specifier for {@link #getDisplayName(int,int,Locale)}
  304. * and {@link #getDisplayNames(int,int,Locale)} stating that names
  305. * should be returned in their short variant if applicable.
  306. *
  307. * @since 1.6
  308. */
  309. public static final int SHORT = 1;
  310. /**
  311. * A style specifier for {@link #getDisplayName(int,int,Locale)}
  312. * and {@link #getDisplayNames(int,int,Locale)} stating that names
  313. * should be returned in their long variant if applicable.
  314. *
  315. * @since 1.6
  316. */
  317. public static final int LONG = 2;
  318. /**
  319. * The time fields. The array is indexed by the constants YEAR to
  320. * DST_OFFSET.
  321. * @serial
  322. */
  323. protected int[] fields = new int[FIELD_COUNT];
  324. /**
  325. * The flags which tell if the fields above have a value.
  326. * @serial
  327. */
  328. protected boolean[] isSet = new boolean[FIELD_COUNT];
  329. /**
  330. * The time in milliseconds since the epoch.
  331. * @serial
  332. */
  333. protected long time;
  334. /**
  335. * Tells if the above field has a valid value.
  336. * @serial
  337. */
  338. protected boolean isTimeSet;
  339. /**
  340. * Tells if the fields have a valid value. This superseeds the isSet
  341. * array.
  342. * @serial
  343. */
  344. protected boolean areFieldsSet;
  345. /**
  346. * The time zone of this calendar. Used by sub classes to do UTC / local
  347. * time conversion. Sub classes can access this field with getTimeZone().
  348. * @serial
  349. */
  350. private TimeZone zone;
  351. /**
  352. * This is the default calendar class, that is returned on
  353. * java.util.Calendar.getInstance().
  354. * XXX - this isn't localized anywhere, is it?
  355. * @see java.util.Calendar#getInstance()
  356. */
  357. private static final String calendarClassName = "java.util.GregorianCalendar";
  358. /**
  359. * Specifies if the date/time interpretation should be lenient.
  360. * If the flag is set, a date such as "February 30, 1996" will be
  361. * treated as the 29th day after the February 1. If this flag
  362. * is false, such dates will cause an exception.
  363. * @serial
  364. */
  365. private boolean lenient;
  366. /**
  367. * Sets what the first day of week is. This is used for
  368. * WEEK_OF_MONTH and WEEK_OF_YEAR fields.
  369. * @serial
  370. */
  371. private int firstDayOfWeek;
  372. /**
  373. * Sets how many days are required in the first week of the year.
  374. * If the first day of the year should be the first week you should
  375. * set this value to 1. If the first week must be a full week, set
  376. * it to 7.
  377. * @serial
  378. */
  379. private int minimalDaysInFirstWeek;
  380. /**
  381. * Is set to true if DST_OFFSET is explicitly set. In that case
  382. * it's value overrides the value computed from the current
  383. * time and the timezone.
  384. */
  385. private boolean explicitDSTOffset = false;
  386. /**
  387. * The version of the serialized data on the stream.
  388. * <dl><dt>0 or not present</dt>
  389. * <dd> JDK 1.1.5 or later.</dd>
  390. * <dt>1</dt>
  391. * <dd>JDK 1.1.6 or later. This always writes a correct `time' value
  392. * on the stream, as well as the other fields, to be compatible with
  393. * earlier versions</dd></dl>
  394. * @since JDK1.1.6
  395. * @serial
  396. */
  397. private int serialVersionOnStream = 1;
  398. /**
  399. * XXX - I have not checked the compatibility. The documentation of
  400. * the serialized-form is quite hairy...
  401. */
  402. static final long serialVersionUID = -1807547505821590642L;
  403. /**
  404. * The name of the resource bundle. Used only by getBundle()
  405. */
  406. private static final String bundleName = "gnu.java.locale.LocaleInformation";
  407. /**
  408. * get resource bundle:
  409. * The resources should be loaded via this method only. Iff an application
  410. * uses this method, the resourcebundle is required.
  411. */
  412. private static ResourceBundle getBundle(Locale locale)
  413. {
  414. return ResourceBundle.getBundle(bundleName, locale,
  415. ClassLoader.getSystemClassLoader());
  416. }
  417. /**
  418. * The set of properties for obtaining the minimum number of days in
  419. * the first week.
  420. */
  421. private static transient final Properties properties;
  422. /**
  423. * Reads in the properties.
  424. */
  425. static
  426. {
  427. properties = new Properties();
  428. try
  429. {
  430. properties.load(Calendar.class.getResourceAsStream("weeks.properties"));
  431. }
  432. catch (IOException exception)
  433. {
  434. System.out.println("Failed to load weeks resource: " + exception);
  435. }
  436. }
  437. /**
  438. * Constructs a new Calendar with the default time zone and the default
  439. * locale.
  440. */
  441. protected Calendar()
  442. {
  443. this(TimeZone.getDefault(), Locale.getDefault());
  444. }
  445. /**
  446. * Constructs a new Calendar with the given time zone and the given
  447. * locale.
  448. * @param zone a time zone.
  449. * @param locale a locale.
  450. */
  451. protected Calendar(TimeZone zone, Locale locale)
  452. {
  453. this.zone = zone;
  454. lenient = true;
  455. String[] days = { "", "sun", "mon", "tue", "wed", "thu", "fri", "sat" };
  456. String country = locale.getCountry();
  457. String min = properties.getProperty("minDays." + country);
  458. if (min == null)
  459. min = properties.getProperty("minDays.DEFAULT");
  460. String first = properties.getProperty("firstDay." + country);
  461. if (first == null)
  462. first = properties.getProperty("firstDay.DEFAULT");
  463. try
  464. {
  465. if (min != null)
  466. minimalDaysInFirstWeek = Integer.parseInt(min);
  467. }
  468. catch (NumberFormatException ex)
  469. {
  470. minimalDaysInFirstWeek = 1;
  471. }
  472. firstDayOfWeek = 1;
  473. if (first != null)
  474. for (int i = 0; i < 8; i++)
  475. if (days[i].equals(first))
  476. firstDayOfWeek = i;
  477. clear();
  478. }
  479. /**
  480. * Creates a calendar representing the actual time, using the default
  481. * time zone and locale.
  482. *
  483. * @return The new calendar.
  484. */
  485. public static synchronized Calendar getInstance()
  486. {
  487. return getInstance(TimeZone.getDefault(), Locale.getDefault());
  488. }
  489. /**
  490. * Creates a calendar representing the actual time, using the given
  491. * time zone and the default locale.
  492. *
  493. * @param zone a time zone (<code>null</code> not permitted).
  494. *
  495. * @return The new calendar.
  496. *
  497. * @throws NullPointerException if <code>zone</code> is <code>null</code>.
  498. */
  499. public static synchronized Calendar getInstance(TimeZone zone)
  500. {
  501. return getInstance(zone, Locale.getDefault());
  502. }
  503. /**
  504. * Creates a calendar representing the actual time, using the default
  505. * time zone and the given locale.
  506. *
  507. * @param locale a locale (<code>null</code> not permitted).
  508. *
  509. * @return The new calendar.
  510. *
  511. * @throws NullPointerException if <code>locale</code> is <code>null</code>.
  512. */
  513. public static synchronized Calendar getInstance(Locale locale)
  514. {
  515. return getInstance(TimeZone.getDefault(), locale);
  516. }
  517. /**
  518. * Cache of locale->calendar-class mappings. This avoids having to do a ResourceBundle
  519. * lookup for every getInstance call.
  520. */
  521. private static final HashMap<Locale,Class> cache = new HashMap<Locale,Class>();
  522. /** Preset argument types for calendar-class constructor lookup. */
  523. private static Class[] ctorArgTypes = new Class[]
  524. {
  525. TimeZone.class, Locale.class
  526. };
  527. /**
  528. * Creates a calendar representing the actual time, using the given
  529. * time zone and locale.
  530. *
  531. * @param zone a time zone (<code>null</code> not permitted).
  532. * @param locale a locale (<code>null</code> not permitted).
  533. *
  534. * @return The new calendar.
  535. *
  536. * @throws NullPointerException if <code>zone</code> or <code>locale</code>
  537. * is <code>null</code>.
  538. */
  539. public static synchronized Calendar getInstance(TimeZone zone, Locale locale)
  540. {
  541. Class calendarClass = cache.get(locale);
  542. Throwable exception = null;
  543. try
  544. {
  545. if (calendarClass == null)
  546. {
  547. calendarClass = Class.forName(calendarClassName);
  548. if (Calendar.class.isAssignableFrom(calendarClass))
  549. cache.put(locale, calendarClass);
  550. }
  551. // GregorianCalendar is by far the most common case. Optimize by
  552. // avoiding reflection.
  553. if (calendarClass == GregorianCalendar.class)
  554. return new GregorianCalendar(zone, locale);
  555. if (Calendar.class.isAssignableFrom(calendarClass))
  556. {
  557. Constructor ctor = calendarClass.getConstructor(ctorArgTypes);
  558. return (Calendar) ctor.newInstance(new Object[] { zone, locale });
  559. }
  560. }
  561. catch (ClassNotFoundException ex)
  562. {
  563. exception = ex;
  564. }
  565. catch (IllegalAccessException ex)
  566. {
  567. exception = ex;
  568. }
  569. catch (NoSuchMethodException ex)
  570. {
  571. exception = ex;
  572. }
  573. catch (InstantiationException ex)
  574. {
  575. exception = ex;
  576. }
  577. catch (InvocationTargetException ex)
  578. {
  579. exception = ex;
  580. }
  581. throw new RuntimeException("Error instantiating calendar for locale "
  582. + locale, exception);
  583. }
  584. /**
  585. * Gets the set of locales for which a Calendar is available.
  586. * @exception MissingResourceException if locale data couldn't be found.
  587. * @return the set of locales.
  588. */
  589. public static synchronized Locale[] getAvailableLocales()
  590. {
  591. ResourceBundle rb = getBundle(new Locale("", ""));
  592. return (Locale[]) rb.getObject("availableLocales");
  593. }
  594. /**
  595. * Converts the time field values (<code>fields</code>) to
  596. * milliseconds since the epoch UTC (<code>time</code>). Override
  597. * this method if you write your own Calendar. */
  598. protected abstract void computeTime();
  599. /**
  600. * Converts the milliseconds since the epoch UTC
  601. * (<code>time</code>) to time fields
  602. * (<code>fields</code>). Override this method if you write your
  603. * own Calendar.
  604. */
  605. protected abstract void computeFields();
  606. /**
  607. * Converts the time represented by this object to a
  608. * <code>Date</code>-Object.
  609. * @return the Date.
  610. */
  611. public final Date getTime()
  612. {
  613. if (! isTimeSet)
  614. computeTime();
  615. return new Date(time);
  616. }
  617. /**
  618. * Sets this Calendar's time to the given Date. All time fields
  619. * are invalidated by this method.
  620. *
  621. * @param date the date (<code>null</code> not permitted).
  622. *
  623. * @throws NullPointerException if <code>date</code> is <code>null</code>.
  624. */
  625. public final void setTime(Date date)
  626. {
  627. setTimeInMillis(date.getTime());
  628. }
  629. /**
  630. * Returns the time represented by this Calendar.
  631. * @return the time in milliseconds since the epoch.
  632. * @specnote This was made public in 1.4.
  633. */
  634. public long getTimeInMillis()
  635. {
  636. if (! isTimeSet)
  637. computeTime();
  638. return time;
  639. }
  640. /**
  641. * Sets this Calendar's time to the given Time. All time fields
  642. * are invalidated by this method.
  643. * @param time the time in milliseconds since the epoch
  644. * @specnote This was made public in 1.4.
  645. */
  646. public void setTimeInMillis(long time)
  647. {
  648. clear();
  649. this.time = time;
  650. isTimeSet = true;
  651. computeFields();
  652. }
  653. /**
  654. * Gets the value of the specified field. They are recomputed
  655. * if they are invalid.
  656. * @param field the time field. One of the time field constants.
  657. * @return the value of the specified field
  658. * @throws ArrayIndexOutOfBoundsException if the field is outside
  659. * the valid range. The value of field must be >= 0 and
  660. * <= <code>FIELD_COUNT</code>.
  661. * @specnote Not final since JDK 1.4
  662. */
  663. public int get(int field)
  664. {
  665. // If the requested field is invalid, force all fields to be recomputed.
  666. if (! isSet[field])
  667. areFieldsSet = false;
  668. complete();
  669. return fields[field];
  670. }
  671. /**
  672. * Gets the value of the specified field. This method doesn't
  673. * recompute the fields, if they are invalid.
  674. * @param field the time field. One of the time field constants.
  675. * @return the value of the specified field, undefined if
  676. * <code>areFieldsSet</code> or <code>isSet[field]</code> is false.
  677. * @throws ArrayIndexOutOfBoundsException if the field is outside
  678. * the valid range. The value of field must be >= 0 and
  679. * <= <code>FIELD_COUNT</code>.
  680. */
  681. protected final int internalGet(int field)
  682. {
  683. return fields[field];
  684. }
  685. /**
  686. * Sets the time field with the given value. This does invalidate
  687. * the time in milliseconds.
  688. * @param field the time field. One of the time field constants
  689. * @param value the value to be set.
  690. * @throws ArrayIndexOutOfBoundsException if field is outside
  691. * the valid range. The value of field must be >= 0 and
  692. * <= <code>FIELD_COUNT</code>.
  693. * @specnote Not final since JDK 1.4
  694. */
  695. public void set(int field, int value)
  696. {
  697. if (isTimeSet)
  698. for (int i = 0; i < FIELD_COUNT; i++)
  699. isSet[i] = false;
  700. isTimeSet = false;
  701. fields[field] = value;
  702. isSet[field] = true;
  703. // The five valid date patterns, in order of priority
  704. // 1 YEAR + MONTH + DAY_OF_MONTH
  705. // 2 YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
  706. // 3 YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
  707. // 4 YEAR + DAY_OF_YEAR
  708. // 5 YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
  709. switch (field)
  710. {
  711. case MONTH: // pattern 1,2 or 3
  712. isSet[DAY_OF_YEAR] = false;
  713. isSet[WEEK_OF_YEAR] = false;
  714. break;
  715. case DAY_OF_MONTH: // pattern 1
  716. isSet[YEAR] = true;
  717. isSet[MONTH] = true;
  718. isSet[WEEK_OF_MONTH] = true;
  719. isSet[DAY_OF_WEEK] = false;
  720. isSet[DAY_OF_WEEK_IN_MONTH] = false;
  721. isSet[DAY_OF_YEAR] = false;
  722. isSet[WEEK_OF_YEAR] = false;
  723. break;
  724. case WEEK_OF_MONTH: // pattern 2
  725. if (! isSet[DAY_OF_WEEK])
  726. fields[DAY_OF_WEEK] = getFirstDayOfWeek();
  727. isSet[YEAR] = true;
  728. isSet[MONTH] = true;
  729. isSet[DAY_OF_WEEK] = true;
  730. isSet[DAY_OF_MONTH] = false;
  731. isSet[DAY_OF_WEEK_IN_MONTH] = false;
  732. isSet[DAY_OF_YEAR] = false;
  733. isSet[WEEK_OF_YEAR] = false;
  734. break;
  735. case DAY_OF_WEEK_IN_MONTH: // pattern 3
  736. if (! isSet[DAY_OF_WEEK])
  737. fields[DAY_OF_WEEK] = getFirstDayOfWeek();
  738. isSet[YEAR] = true;
  739. isSet[MONTH] = true;
  740. isSet[DAY_OF_WEEK] = true;
  741. isSet[DAY_OF_YEAR] = false;
  742. isSet[DAY_OF_MONTH] = false;
  743. isSet[WEEK_OF_MONTH] = false;
  744. isSet[WEEK_OF_YEAR] = false;
  745. break;
  746. case DAY_OF_YEAR: // pattern 4
  747. isSet[YEAR] = true;
  748. isSet[MONTH] = false;
  749. isSet[WEEK_OF_MONTH] = false;
  750. isSet[DAY_OF_MONTH] = false;
  751. isSet[DAY_OF_WEEK] = false;
  752. isSet[WEEK_OF_YEAR] = false;
  753. isSet[DAY_OF_WEEK_IN_MONTH] = false;
  754. break;
  755. case WEEK_OF_YEAR: // pattern 5
  756. if (! isSet[DAY_OF_WEEK])
  757. fields[DAY_OF_WEEK] = getFirstDayOfWeek();
  758. isSet[YEAR] = true;
  759. isSet[DAY_OF_WEEK] = true;
  760. isSet[MONTH] = false;
  761. isSet[DAY_OF_MONTH] = false;
  762. isSet[WEEK_OF_MONTH] = false;
  763. isSet[DAY_OF_YEAR] = false;
  764. isSet[DAY_OF_WEEK_IN_MONTH] = false;
  765. break;
  766. case AM_PM:
  767. isSet[HOUR] = true;
  768. isSet[HOUR_OF_DAY] = false;
  769. break;
  770. case HOUR_OF_DAY:
  771. isSet[AM_PM] = false;
  772. isSet[HOUR] = false;
  773. break;
  774. case HOUR:
  775. isSet[AM_PM] = true;
  776. isSet[HOUR_OF_DAY] = false;
  777. break;
  778. case DST_OFFSET:
  779. explicitDSTOffset = true;
  780. }
  781. // May have crossed over a DST boundary.
  782. if (! explicitDSTOffset && (field != DST_OFFSET && field != ZONE_OFFSET))
  783. isSet[DST_OFFSET] = false;
  784. }
  785. /**
  786. * Sets the fields for year, month, and date
  787. * @param year the year.
  788. * @param month the month, one of the constants JANUARY..UNDICEMBER.
  789. * @param date the day of the month
  790. */
  791. public final void set(int year, int month, int date)
  792. {
  793. isTimeSet = false;
  794. fields[YEAR] = year;
  795. fields[MONTH] = month;
  796. fields[DATE] = date;
  797. isSet[YEAR] = isSet[MONTH] = isSet[DATE] = true;
  798. isSet[WEEK_OF_YEAR] = false;
  799. isSet[DAY_OF_YEAR] = false;
  800. isSet[WEEK_OF_MONTH] = false;
  801. isSet[DAY_OF_WEEK] = false;
  802. isSet[DAY_OF_WEEK_IN_MONTH] = false;
  803. isSet[ERA] = false;
  804. if (! explicitDSTOffset)
  805. isSet[DST_OFFSET] = false; // May have crossed a DST boundary.
  806. }
  807. /**
  808. * Sets the fields for year, month, date, hour, and minute
  809. * @param year the year.
  810. * @param month the month, one of the constants JANUARY..UNDICEMBER.
  811. * @param date the day of the month
  812. * @param hour the hour of day.
  813. * @param minute the minute.
  814. */
  815. public final void set(int year, int month, int date, int hour, int minute)
  816. {
  817. set(year, month, date);
  818. fields[HOUR_OF_DAY] = hour;
  819. fields[MINUTE] = minute;
  820. isSet[HOUR_OF_DAY] = isSet[MINUTE] = true;
  821. isSet[AM_PM] = false;
  822. isSet[HOUR] = false;
  823. }
  824. /**
  825. * Sets the fields for year, month, date, hour, and minute
  826. * @param year the year.
  827. * @param month the month, one of the constants JANUARY..UNDICEMBER.
  828. * @param date the day of the month
  829. * @param hour the hour of day.
  830. * @param minute the minute.
  831. * @param second the second.
  832. */
  833. public final void set(int year, int month, int date, int hour, int minute,
  834. int second)
  835. {
  836. set(year, month, date, hour, minute);
  837. fields[SECOND] = second;
  838. isSet[SECOND] = true;
  839. }
  840. /**
  841. * Clears the values of all the time fields.
  842. */
  843. public final void clear()
  844. {
  845. isTimeSet = false;
  846. areFieldsSet = false;
  847. int zoneOffs = zone.getRawOffset();
  848. int[] tempFields =
  849. {
  850. 1, 1970, JANUARY, 1, 1, 1, 1, THURSDAY, 1, AM, 0, 0, 0,
  851. 0, 0, zoneOffs, 0
  852. };
  853. fields = tempFields;
  854. for (int i = 0; i < FIELD_COUNT; i++)
  855. isSet[i] = false;
  856. }
  857. /**
  858. * Clears the values of the specified time field.
  859. * @param field the time field. One of the time field constants.
  860. * @throws ArrayIndexOutOfBoundsException if field is outside
  861. * the valid range. The value of field must be >= 0 and
  862. * <= <code>FIELD_COUNT</code>.
  863. */
  864. public final void clear(int field)
  865. {
  866. int[] tempFields =
  867. {
  868. 1, 1970, JANUARY, 1, 1, 1, 1, THURSDAY, 1, AM, 0, 0, 0,
  869. 0, 0, zone.getRawOffset(), 0
  870. };
  871. complete();
  872. isTimeSet = false;
  873. areFieldsSet = false;
  874. isSet[field] = false;
  875. fields[field] = tempFields[field];
  876. }
  877. /**
  878. * Determines if the specified field has a valid value.
  879. * @return true if the specified field has a value.
  880. * @throws ArrayIndexOutOfBoundsException if the field is outside
  881. * the valid range. The value of field must be >= 0 and
  882. * <= <code>FIELD_COUNT</code>.
  883. */
  884. public final boolean isSet(int field)
  885. {
  886. return isSet[field];
  887. }
  888. /**
  889. * Fills any unset fields in the time field list
  890. */
  891. protected void complete()
  892. {
  893. if (! isTimeSet)
  894. computeTime();
  895. if (! areFieldsSet)
  896. computeFields();
  897. }
  898. /**
  899. * Compares the given calendar with this.
  900. * @param o the object to that we should compare.
  901. * @return true, if the given object is a calendar, that represents
  902. * the same time (but doesn't necessary have the same fields).
  903. */
  904. public boolean equals(Object o)
  905. {
  906. if (! (o instanceof Calendar))
  907. return false;
  908. Calendar cal = (Calendar) o;
  909. if (getTimeInMillis() == ((Calendar) o).getTimeInMillis()
  910. && cal.getFirstDayOfWeek() == getFirstDayOfWeek()
  911. && cal.isLenient() == isLenient()
  912. && cal.getMinimalDaysInFirstWeek() == getMinimalDaysInFirstWeek())
  913. {
  914. TimeZone self = getTimeZone();
  915. TimeZone oth = cal.getTimeZone();
  916. return self == null ? oth == null : self.equals(oth);
  917. }
  918. return false;
  919. }
  920. /**
  921. * Returns a hash code for this calendar.
  922. * @return a hash code, which fullfits the general contract of
  923. * <code>hashCode()</code>
  924. */
  925. public int hashCode()
  926. {
  927. long time = getTimeInMillis();
  928. int val = (int) ((time & 0xffffffffL) ^ (time >> 32));
  929. val += (getFirstDayOfWeek() + (isLenient() ? 1230 : 1237)
  930. + getMinimalDaysInFirstWeek());
  931. TimeZone self = getTimeZone();
  932. if (self != null)
  933. val ^= self.hashCode();
  934. return val;
  935. }
  936. /**
  937. * Compares the given calendar with this.
  938. * @param o the object to that we should compare.
  939. * @return true, if the given object is a calendar, and this calendar
  940. * represents a smaller time than the calendar o.
  941. * @exception ClassCastException if o is not an calendar.
  942. * @since JDK1.2 you don't need to override this method
  943. */
  944. public boolean before(Object o)
  945. {
  946. return getTimeInMillis() < ((Calendar) o).getTimeInMillis();
  947. }
  948. /**
  949. * Compares the given calendar with this.
  950. * @param o the object to that we should compare.
  951. * @return true, if the given object is a calendar, and this calendar
  952. * represents a bigger time than the calendar o.
  953. * @exception ClassCastException if o is not an calendar.
  954. * @since JDK1.2 you don't need to override this method
  955. */
  956. public boolean after(Object o)
  957. {
  958. return getTimeInMillis() > ((Calendar) o).getTimeInMillis();
  959. }
  960. /**
  961. * Adds the specified amount of time to the given time field. The
  962. * amount may be negative to subtract the time. If the field overflows
  963. * it does what you expect: Jan, 25 + 10 Days is Feb, 4.
  964. * @param field the time field. One of the time field constants.
  965. * @param amount the amount of time.
  966. * @throws ArrayIndexOutOfBoundsException if the field is outside
  967. * the valid range. The value of field must be >= 0 and
  968. * <= <code>FIELD_COUNT</code>.
  969. */
  970. public abstract void add(int field, int amount);
  971. /**
  972. * Rolls the specified time field up or down. This means add one
  973. * to the specified field, but don't change the other fields. If
  974. * the maximum for this field is reached, start over with the
  975. * minimum value. <br>
  976. *
  977. * <strong>Note:</strong> There may be situation, where the other
  978. * fields must be changed, e.g rolling the month on May, 31.
  979. * The date June, 31 is automatically converted to July, 1.
  980. * @param field the time field. One of the time field constants.
  981. * @param up the direction, true for up, false for down.
  982. * @throws ArrayIndexOutOfBoundsException if the field is outside
  983. * the valid range. The value of field must be >= 0 and
  984. * <= <code>FIELD_COUNT</code>.
  985. */
  986. public abstract void roll(int field, boolean up);
  987. /**
  988. * Rolls up or down the specified time field by the given amount.
  989. * A negative amount rolls down. The default implementation is
  990. * call <code>roll(int, boolean)</code> for the specified amount.
  991. *
  992. * Subclasses should override this method to do more intuitiv things.
  993. *
  994. * @param field the time field. One of the time field constants.
  995. * @param amount the amount to roll by, positive for rolling up,
  996. * negative for rolling down.
  997. * @throws ArrayIndexOutOfBoundsException if the field is outside
  998. * the valid range. The value of field must be >= 0 and
  999. * <= <code>FIELD_COUNT</code>.
  1000. * @since JDK1.2
  1001. */
  1002. public void roll(int field, int amount)
  1003. {
  1004. while (amount > 0)
  1005. {
  1006. roll(field, true);
  1007. amount--;
  1008. }
  1009. while (amount < 0)
  1010. {
  1011. roll(field, false);
  1012. amount++;
  1013. }
  1014. }
  1015. /**
  1016. * Sets the time zone to the specified value.
  1017. * @param zone the new time zone
  1018. */
  1019. public void setTimeZone(TimeZone zone)
  1020. {
  1021. this.zone = zone;
  1022. computeTime();
  1023. computeFields();
  1024. }
  1025. /**
  1026. * Gets the time zone of this calendar
  1027. * @return the current time zone.
  1028. */
  1029. public TimeZone getTimeZone()
  1030. {
  1031. return zone;
  1032. }
  1033. /**
  1034. * Specifies if the date/time interpretation should be lenient.
  1035. * If the flag is set, a date such as "February 30, 1996" will be
  1036. * treated as the 29th day after the February 1. If this flag
  1037. * is false, such dates will cause an exception.
  1038. * @param lenient true, if the date should be interpreted linient,
  1039. * false if it should be interpreted strict.
  1040. */
  1041. public void setLenient(boolean lenient)
  1042. {
  1043. this.lenient = lenient;
  1044. }
  1045. /**
  1046. * Tells if the date/time interpretation is lenient.
  1047. * @return true, if the date should be interpreted linient,
  1048. * false if it should be interpreted strict.
  1049. */
  1050. public boolean isLenient()
  1051. {
  1052. return lenient;
  1053. }
  1054. /**
  1055. * Sets what the first day of week is. This is used for
  1056. * WEEK_OF_MONTH and WEEK_OF_YEAR fields.
  1057. * @param value the first day of week. One of SUNDAY to SATURDAY.
  1058. */
  1059. public void setFirstDayOfWeek(int value)
  1060. {
  1061. firstDayOfWeek = value;
  1062. }
  1063. /**
  1064. * Gets what the first day of week is. This is used for
  1065. * WEEK_OF_MONTH and WEEK_OF_YEAR fields.
  1066. * @return the first day of week. One of SUNDAY to SATURDAY.
  1067. */
  1068. public int getFirstDayOfWeek()
  1069. {
  1070. return firstDayOfWeek;
  1071. }
  1072. /**
  1073. * Sets how many days are required in the first week of the year.
  1074. * If the first day of the year should be the first week you should
  1075. * set this value to 1. If the first week must be a full week, set
  1076. * it to 7.
  1077. * @param value the minimal days required in the first week.
  1078. */
  1079. public void setMinimalDaysInFirstWeek(int value)
  1080. {
  1081. minimalDaysInFirstWeek = value;
  1082. }
  1083. /**
  1084. * Gets how many days are required in the first week of the year.
  1085. * @return the minimal days required in the first week.
  1086. * @see #setMinimalDaysInFirstWeek
  1087. */
  1088. public int getMinimalDaysInFirstWeek()
  1089. {
  1090. return minimalDaysInFirstWeek;
  1091. }
  1092. /**
  1093. * Gets the smallest value that is allowed for the specified field.
  1094. * @param field the time field. One of the time field constants.
  1095. * @return the smallest value.
  1096. */
  1097. public abstract int getMinimum(int field);
  1098. /**
  1099. * Gets the biggest value that is allowed for the specified field.
  1100. * @param field the time field. One of the time field constants.
  1101. * @return the biggest value.
  1102. */
  1103. public abstract int getMaximum(int field);
  1104. /**
  1105. * Gets the greatest minimum value that is allowed for the specified field.
  1106. * @param field the time field. One of the time field constants.
  1107. * @return the greatest minimum value.
  1108. */
  1109. public abstract int getGreatestMinimum(int field);
  1110. /**
  1111. * Gets the smallest maximum value that is allowed for the
  1112. * specified field. For example this is 28 for DAY_OF_MONTH.
  1113. * @param field the time field. One of the time field constants.
  1114. * @return the least maximum value.
  1115. */
  1116. public abstract int getLeastMaximum(int field);
  1117. /**
  1118. * Gets the actual minimum value that is allowed for the specified field.
  1119. * This value is dependent on the values of the other fields.
  1120. * @param field the time field. One of the time field constants.
  1121. * @return the actual minimum value.
  1122. * @throws ArrayIndexOutOfBoundsException if the field is outside
  1123. * the valid range. The value of field must be >= 0 and
  1124. * <= <code>FIELD_COUNT</code>.
  1125. * @since jdk1.2
  1126. */
  1127. public int getActualMinimum(int field)
  1128. {
  1129. Calendar tmp = (Calendar) clone(); // To avoid restoring state
  1130. int min = tmp.getGreatestMinimum(field);
  1131. int end = tmp.getMinimum(field);
  1132. tmp.set(field, min);
  1133. for (; min > end; min--)
  1134. {
  1135. tmp.add(field, -1); // Try to get smaller
  1136. if (tmp.get(field) != min - 1)
  1137. break; // Done if not successful
  1138. }
  1139. return min;
  1140. }
  1141. /**
  1142. * Gets the actual maximum value that is allowed for the specified field.
  1143. * This value is dependent on the values of the other fields.
  1144. * @param field the time field. One of the time field constants.
  1145. * @return the actual maximum value.
  1146. * @throws ArrayIndexOutOfBoundsException if the field is outside
  1147. * the valid range. The value of field must be >= 0 and
  1148. * <= <code>FIELD_COUNT</code>.
  1149. * @since jdk1.2
  1150. */
  1151. public int getActualMaximum(int field)
  1152. {
  1153. Calendar tmp = (Calendar) clone(); // To avoid restoring state
  1154. int max = tmp.getLeastMaximum(field);
  1155. int end = tmp.getMaximum(field);
  1156. tmp.set(field, max);
  1157. for (; max < end; max++)
  1158. {
  1159. tmp.add(field, 1);
  1160. if (tmp.get(field) != max + 1)
  1161. break;
  1162. }
  1163. return max;
  1164. }
  1165. /**
  1166. * Compares the time of two calendar instances.
  1167. * @param cal the calendar to which the time should be compared.
  1168. * @return 0 if the two calendars are set to the same time,
  1169. * less than 0 if the time of this calendar is before that of
  1170. * <code>cal</code>, or more than 0 if the time of this calendar is after
  1171. * that of <code>cal</code>.
  1172. *
  1173. * @param cal the calendar to compare this instance with.
  1174. * @throws NullPointerException if <code>cal</code> is null.
  1175. * @throws IllegalArgumentException if either calendar has fields set to
  1176. * invalid values.
  1177. * @since 1.5
  1178. */
  1179. public int compareTo(Calendar cal)
  1180. {
  1181. long t1 = getTimeInMillis();
  1182. long t2 = cal.getTimeInMillis();
  1183. if(t1 == t2)
  1184. return 0;
  1185. if(t1 > t2)
  1186. return 1;
  1187. return -1;
  1188. }
  1189. /**
  1190. * Return a clone of this object.
  1191. */
  1192. public Object clone()
  1193. {
  1194. try
  1195. {
  1196. Calendar cal = (Calendar) super.clone();
  1197. cal.fields = (int[]) fields.clone();
  1198. cal.isSet = (boolean[]) isSet.clone();
  1199. return cal;
  1200. }
  1201. catch (CloneNotSupportedException ex)
  1202. {
  1203. return null;
  1204. }
  1205. }
  1206. private static final String[] fieldNames =
  1207. {
  1208. ",ERA=", ",YEAR=", ",MONTH=",
  1209. ",WEEK_OF_YEAR=",
  1210. ",WEEK_OF_MONTH=",
  1211. ",DAY_OF_MONTH=",
  1212. ",DAY_OF_YEAR=", ",DAY_OF_WEEK=",
  1213. ",DAY_OF_WEEK_IN_MONTH=",
  1214. ",AM_PM=", ",HOUR=",
  1215. ",HOUR_OF_DAY=", ",MINUTE=",
  1216. ",SECOND=", ",MILLISECOND=",
  1217. ",ZONE_OFFSET=", ",DST_OFFSET="
  1218. };
  1219. /**
  1220. * Returns a string representation of this object. It is mainly
  1221. * for debugging purposes and its content is implementation
  1222. * specific.
  1223. */
  1224. public String toString()
  1225. {
  1226. CPStringBuilder sb = new CPStringBuilder(getClass().getName());
  1227. sb.append('[');
  1228. sb.append("time=");
  1229. if (isTimeSet)
  1230. sb.append(time);
  1231. else
  1232. sb.append("?");
  1233. sb.append(",zone=" + zone);
  1234. sb.append(",areFieldsSet=" + areFieldsSet);
  1235. for (int i = 0; i < FIELD_COUNT; i++)
  1236. {
  1237. sb.append(fieldNames[i]);
  1238. if (isSet[i])
  1239. sb.append(fields[i]);
  1240. else
  1241. sb.append("?");
  1242. }
  1243. sb.append(",lenient=").append(lenient);
  1244. sb.append(",firstDayOfWeek=").append(firstDayOfWeek);
  1245. sb.append(",minimalDaysInFirstWeek=").append(minimalDaysInFirstWeek);
  1246. sb.append("]");
  1247. return sb.toString();
  1248. }
  1249. /**
  1250. * Saves the state of the object to the stream. Ideally we would
  1251. * only write the time field, but we need to be compatible with
  1252. * earlier versions. <br>
  1253. *
  1254. * This doesn't write the JDK1.1 field nextStamp to the stream, as
  1255. * I don't know what it is good for, and because the documentation
  1256. * says, that it could be omitted. */
  1257. private void writeObject(ObjectOutputStream stream) throws IOException
  1258. {
  1259. if (! isTimeSet)
  1260. computeTime();
  1261. stream.defaultWriteObject();
  1262. }
  1263. /**
  1264. * Reads the object back from stream (deserialization).
  1265. */
  1266. private void readObject(ObjectInputStream stream)
  1267. throws IOException, ClassNotFoundException
  1268. {
  1269. stream.defaultReadObject();
  1270. if (! isTimeSet)
  1271. computeTime();
  1272. if (serialVersionOnStream > 1)
  1273. {
  1274. // This is my interpretation of the serial number:
  1275. // Sun wants to remove all fields from the stream someday
  1276. // and will then increase the serialVersion number again.
  1277. // We prepare to be compatible.
  1278. fields = new int[FIELD_COUNT];
  1279. isSet = new boolean[FIELD_COUNT];
  1280. areFieldsSet = false;
  1281. }
  1282. }
  1283. /**
  1284. * Returns a localised textual representation of the current value
  1285. * of the given field using the specified style. If there is no
  1286. * applicable textual representation (e.g. the field has a numeric
  1287. * value), then <code>null</code> is returned. If one does exist,
  1288. * then the value is obtained from {@link #get(int)} and converted
  1289. * appropriately. For example, if the <code>MONTH</code> field is
  1290. * requested, then <code>get(MONTH)</code> is called. This is then
  1291. * converted to a textual representation based on its value and
  1292. * the style requested; if the <code>LONG</code> style is requested
  1293. * and the returned value is <code>11</code> from a
  1294. * {@link GregorianCalendar} implementation, then <code>"December"</code>
  1295. * is returned. By default, a textual representation is available
  1296. * for all fields which have an applicable value obtainable from
  1297. * {@link java.text.DateFormatSymbols}.
  1298. *
  1299. * @param field the calendar field whose textual representation should
  1300. * be obtained.
  1301. * @param style the style to use; either {@link #LONG} or {@link #SHORT}.
  1302. * @param locale the locale to use for translation.
  1303. * @return the textual representation of the given field in the specified
  1304. * style, or <code>null</code> if none is applicable.
  1305. * @throws IllegalArgumentException if <code>field</code> or <code>style</code>
  1306. * or invalid, or the calendar is non-lenient
  1307. * and has invalid values.
  1308. * @throws NullPointerException if <code>locale</code> is <code>null</code>.
  1309. * @since 1.6
  1310. */
  1311. public String getDisplayName(int field, int style, Locale locale)
  1312. {
  1313. if (field < 0 || field >= FIELD_COUNT)
  1314. throw new IllegalArgumentException("The field value, " + field +
  1315. ", is invalid.");
  1316. if (style != SHORT && style != LONG)
  1317. throw new IllegalArgumentException("The style must be either " +
  1318. "short or long.");
  1319. if (field == YEAR || field == WEEK_OF_YEAR ||
  1320. field == WEEK_OF_MONTH || field == DAY_OF_MONTH ||
  1321. field == DAY_OF_YEAR || field == DAY_OF_WEEK_IN_MONTH ||
  1322. field == HOUR || field == HOUR_OF_DAY || field == MINUTE ||
  1323. field == SECOND || field == MILLISECOND)
  1324. return null;
  1325. int value = get(field);
  1326. DateFormatSymbols syms = DateFormatSymbols.getInstance(locale);
  1327. if (field == ERA)
  1328. return syms.getEras()[value];
  1329. if (field == MONTH)
  1330. if (style == LONG)
  1331. return syms.getMonths()[value];
  1332. else
  1333. return syms.getShortMonths()[value];
  1334. if (field == DAY_OF_WEEK)
  1335. if (style == LONG)
  1336. return syms.getWeekdays()[value];
  1337. else
  1338. return syms.getShortWeekdays()[value];
  1339. if (field == AM_PM)
  1340. return syms.getAmPmStrings()[value];
  1341. if (field == ZONE_OFFSET)
  1342. if (style == LONG)
  1343. return syms.getZoneStrings()[value][1];
  1344. else
  1345. return syms.getZoneStrings()[value][2];
  1346. if (field == DST_OFFSET)
  1347. if (style == LONG)
  1348. return syms.getZoneStrings()[value][3];
  1349. else
  1350. return syms.getZoneStrings()[value][4];
  1351. throw new InternalError("Failed to resolve field " + field +
  1352. " with style " + style + " for locale " +
  1353. locale);
  1354. }
  1355. /**
  1356. * Returns a map linking all specified textual representations
  1357. * of the given field to their numerical values. The textual
  1358. * representations included are determined by the specified
  1359. * style and locale. For example, if the style <code>LONG</code>
  1360. * is specified and the German locale, then the map will
  1361. * contain "Montag" to {@link #MONDAY}, "Dienstag" to
  1362. * {@link #TUESDAY}, "Mittwoch" to {@link #WEDNESDAY} and
  1363. * so on. The default implementation uses the values returned
  1364. * by {@link DateFormatSymbols} so, for example, the style
  1365. * {@link #ALL_STYLES} and the field {@link #MONTH} will return
  1366. * a map filled with the values returned from
  1367. * {@link DateFormatSymbols#getMonths()} and
  1368. * {@link DateFormatSymbols#getShortMonths()}. If there are
  1369. * no textual representations for a given field (usually because
  1370. * it is purely numeric, such as the year in the
  1371. * {@link GregorianCalendar}), <code>null</code> is returned.
  1372. *
  1373. * @param field the calendar field whose textual representation should
  1374. * be obtained.
  1375. * @param style the style to use; either {@link #LONG}, {@link #SHORT}
  1376. * or {@link ALL_STYLES}.
  1377. * @param locale the locale to use for translation.
  1378. * @return a map of the textual representations of the given field in the
  1379. * specified style to their numeric values, or <code>null</code>
  1380. * if none is applicable.
  1381. * @throws IllegalArgumentException if <code>field</code> or <code>style</code>
  1382. * or invalid, or the calendar is non-lenient
  1383. * and has invalid values.
  1384. * @throws NullPointerException if <code>locale</code> is <code>null</code>.
  1385. * @since 1.6
  1386. */
  1387. public Map<String,Integer> getDisplayNames(int field, int style, Locale locale)
  1388. {
  1389. if (field < 0 || field >= FIELD_COUNT)
  1390. throw new IllegalArgumentException("The field value, " + field +
  1391. ", is invalid.");
  1392. if (style != SHORT && style != LONG && style != ALL_STYLES)
  1393. throw new IllegalArgumentException("The style must be either " +
  1394. "short, long or all styles.");
  1395. if (field == YEAR || field == WEEK_OF_YEAR ||
  1396. field == WEEK_OF_MONTH || field == DAY_OF_MONTH ||
  1397. field == DAY_OF_YEAR || field == DAY_OF_WEEK_IN_MONTH ||
  1398. field == HOUR || field == HOUR_OF_DAY || field == MINUTE ||
  1399. field == SECOND || field == MILLISECOND)
  1400. return null;
  1401. DateFormatSymbols syms = DateFormatSymbols.getInstance(locale);
  1402. Map<String,Integer> map = new HashMap<String,Integer>();
  1403. if (field == ERA)
  1404. {
  1405. String[] eras = syms.getEras();
  1406. for (int a = 0; a < eras.length; ++a)
  1407. map.put(eras[a], a);
  1408. return map;
  1409. }
  1410. if (field == MONTH)
  1411. {
  1412. if (style == LONG || style == ALL_STYLES)
  1413. {
  1414. String[] months = syms.getMonths();
  1415. for (int a = 0; a < months.length; ++a)
  1416. map.put(months[a], a);
  1417. }
  1418. if (style == SHORT || style == ALL_STYLES)
  1419. {
  1420. String[] months = syms.getShortMonths();
  1421. for (int a = 0; a < months.length; ++a)
  1422. map.put(months[a], a);
  1423. }
  1424. return map;
  1425. }
  1426. if (field == DAY_OF_WEEK)
  1427. {
  1428. if (style == LONG || style == ALL_STYLES)
  1429. {
  1430. String[] weekdays = syms.getWeekdays();
  1431. for (int a = SUNDAY; a < weekdays.length; ++a)
  1432. map.put(weekdays[a], a);
  1433. }
  1434. if (style == SHORT || style == ALL_STYLES)
  1435. {
  1436. String[] weekdays = syms.getShortWeekdays();
  1437. for (int a = SUNDAY; a < weekdays.length; ++a)
  1438. map.put(weekdays[a], a);
  1439. }
  1440. return map;
  1441. }
  1442. if (field == AM_PM)
  1443. {
  1444. String[] ampms = syms.getAmPmStrings();
  1445. for (int a = 0; a < ampms.length; ++a)
  1446. map.put(ampms[a], a);
  1447. return map;
  1448. }
  1449. if (field == ZONE_OFFSET)
  1450. {
  1451. String[][] zones = syms.getZoneStrings();
  1452. for (int a = 0; a < zones.length; ++a)
  1453. {
  1454. if (style == LONG || style == ALL_STYLES)
  1455. map.put(zones[a][1], a);
  1456. if (style == SHORT || style == ALL_STYLES)
  1457. map.put(zones[a][2], a);
  1458. }
  1459. return map;
  1460. }
  1461. if (field == DST_OFFSET)
  1462. {
  1463. String[][] zones = syms.getZoneStrings();
  1464. for (int a = 0; a < zones.length; ++a)
  1465. {
  1466. if (style == LONG || style == ALL_STYLES)
  1467. map.put(zones[a][3], a);
  1468. if (style == SHORT || style == ALL_STYLES)
  1469. map.put(zones[a][4], a);
  1470. }
  1471. return map;
  1472. }
  1473. throw new InternalError("Failed to resolve field " + field +
  1474. " with style " + style + " for locale " +
  1475. locale);
  1476. }
  1477. }