1--- 2layout: default 3title: Calendar Services 4nav_order: 1 5parent: Date/Time 6--- 7<!-- 8© 2020 and later: Unicode, Inc. and others. 9License & terms of use: http://www.unicode.org/copyright.html 10--> 11 12# Calendar Classes 13{: .no_toc } 14 15## Contents 16{: .no_toc .text-delta } 17 181. TOC 19{:toc} 20 21--- 22 23## Overview 24 25ICU has two main calendar classes used for parsing and formatting Calendar 26information correctly: 27 281. `Calendar` 29 30 An abstract base class that defines the calendar API. This API supports 31 UDate to fields conversion and field arithmetic. 32 332. `GregorianCalendar` 34 35 A concrete subclass of `Calendar` that implements the standard calendar used 36 today internationally. 37 38In addition to these, ICU has other `Calendar` subclasses to support 39non-gregorian calendars including: 40 41* Japanese 42 43* Buddhist 44 45* Chinese 46 47* Persian 48 49* Indian 50 51* Islamic 52 53* Hebrew 54 55* Indian 56 57* Coptic 58 59* Ethiopic 60 61The `Calendar` class is designed to support additional calendar systems in the future. 62 63> :point_right: **Note**: *`Calendar` classes are related to `UDate`, the `TimeZone` classes, and the `DateFormat` 64classes.* 65 66### Calendar locale and keyword handling 67 68When a calendar object is created, via either `Calendar::create()`, or 69`ucal_open()`, or indirectly within a date formatter, ICU looks up the 'default' 70calendar type for that locale. At present, all locales default to a Gregorian 71calendar, except for the compatibility locales th_TH_TRADITIONAL and 72ja_JP_TRADITIONAL. If the "calendar" keyword is supplied, this value will 73override the default for that locale. 74 75For instance, `Calendar::createInstance("fr_FR", status)` will create a Gregorian calendar, 76but `Calendar::createInstance("fr_FR@calendar=buddhist")` will create a Buddhist calendar. 77 78It is an error to use an invalid calendar type. It will produce a missing resource error. 79 80> :point_right: **Note**: *As of ICU 2.8, the above description applies to ICU4J only. ICU4J will have 81this behavior in 3.0* 82 83## Usage 84 85This section discusses how to use the `Calendar` class and the `GregorianCalendar` subclass. 86 87### Calendar 88 89`Calendar` is an abstract base class. It defines common protocols for a hierarchy 90of classes. Concrete subclasses of `Calendar`, for example the `GregorianCalendar` 91class, define specific operations that correspond to a real-world calendar 92system. `Calendar` objects (instantiations of concrete subclasses of `Calendar`), 93embody state that represents a specific context. They correspond to a real-world 94locale. They also contain state that specifies a moment in time. 95 96The API defined by `Calendar` encompasses multiple functions: 97 981. Representation of a specific time as a `UDate` 99 1002. Representation of a specific time as a set of integer fields, such as `YEAR`, 101 `MONTH`, `HOUR`, etc. 102 1033. Conversion from `UDate` to fields 104 1054. Conversion from fields to `UDate` 106 1075. Field arithmetic, including adding, rolling, and field difference 108 1096. Context management 110 1117. Factory methods 112 1138. Miscellaneous: field meta-information, time comparison 114 115#### Representation and Conversion 116 117The basic function of the `Calendar` class is to convert between a `UDate` value and 118a set of integer fields. A `UDate` value is stored as UTC time in milliseconds, 119which means it is calendar and time zone independent. `UDate` is the most compact 120and portable way to store and transmit a date and time. `Integer` field values, on 121the other hand, depend on the calendar system (that is, the concrete subclass of 122`Calendar`) and the calendar object's context state. 123 124> :point_right: **Note**: *`Integer` field values are needed when implementing a human interface that must 125display or input a date and/or time.* 126 127At any given time, a calendar object uses (when `DateFormat` is not sufficient) 128either its internal `UDate` or its integer fields (depending on which has been set 129most recently via `setTime()` or `set()`), to represent a specific date and time. 130Whatever the current internal representation, when the caller requests a `UDate` 131or an integer field it is computed if necessary. The caller need never trigger 132the conversion explicitly. The caller must perform a conversion to set either 133the `UDate` or the integer fields, and then retrieve the desired data. This also 134applies in situations where the caller has some integer fields and wants to 135obtain others. 136 137#### Field Arithmetic 138 139Arithmetic with `UDate` values is straightforward. Since the values are 140millisecond scalar values, direct addition and subtraction is all that is 141required. Arithmetic with integer fields is more complicated. For example, what 142is the date June 4, 1999 plus 300 days? `Calendar` defines three basic methods (in 143several variants) that perform field arithmetic: `add()`, `roll()`, and 144`fieldDifference()`. 145 146The `add()` method adds positive or negative values to a specified field. For 147example, calling `add(Calendar::MONTH, 2)` on a `GregorianCalendar` object set to 148March 15, 1999 sets the calendar to May 15, 1999. The `roll()` method is similar, 149but does not modify fields that are larger. For example, calling 150`roll(Calendar::HOUR, n)` changes the hour that a calendar is set to without 151changing the day. Calling `roll(Calendar::MONTH, n)` changes the month without 152changing the year. 153 154The `fieldDifference()` method is the inverse of the `add()` method. It computes the 155difference between a calendar's currently set time and a specified `UDate` in 156terms of a specified field. Repeated calls to `fieldDifference()` compute the 157difference between two `UDate` objects in terms of whatever fields the caller specifies 158(for example, years, months, days, and hours). If the `add()` method is called 159with the results of `fieldDifference(when, n)`, then the calendar is moved toward 160field by field. 161 162This is demonstrated in the following example: 163 164```c++ 165Calendar cal = Calendar.getInstance(); 166cal.set(2000, Calendar.MARCH, 15); 167Date date = new Date(2000-1900, Calendar.JULY, 4); 168int yearDiff = cal.fieldDifference(date, Calendar.YEAR); // yearDiff <= 0 169int monthDiff = cal.fieldDifference(date, Calendar.MONTH); // monthDiff ;<= 3 170// At this point cal has been advanced 3 months to June 15, 2000. 171int dayDiff = cal.fieldDifference(date, Calendar.DAY_OF_MONTH); // dayDiff ;<=19 172// At this point cal has been advanced 19 days to July 4, 2000. 173``` 174 175#### Context Management 176 177A `Calendar` object performs its computations within a specific context. The 178context affects the results of conversions and arithmetic computations. When a 179`Calendar` object is created, it establishes its context using either default 180values or values specified by the caller: 181 1821. Locale-specific week data, including the first day of the week and the 183 minimal days in the first week. Initially, this is retrieved from the locale 184 resource data for the specified locale, or if none is specified, for the 185 default locale. 186 1872. A `TimeZone` object. Initially, this is set to the specified zone object, or 188 if none is specified, the default `TimeZone`. 189 190The context of a `Calendar` object can be queried after the calendar is created 191using calls such as `getMinimalDaysInFirstWeek()`, `getFirstDayOfWeek()`, and 192`getTimeZone()`. The context can be changed using calls such as 193`setMinimalDaysInFirstWeek()`, `setFirstDayOfWeek()`, and `setTimeZone()`. 194 195#### Factory Methods 196 197Like other format classes, the best way to create a calendar object is by using 198one of the factory methods. These are static methods on the `Calendar` class that 199create and return an instance of a concrete subclass. Factory methods should be 200used to enable the code to obtain the correct calendar for a locale without 201having to know specific details. The factory methods on `Calendar` are named 202`createInstance()`. 203 204***`MONTH` field*** 205> :point_right: **Note**: *Calendar numbers months starting from zero, so calling `cal.set(1998, 3, 5)` 206sets cal to April 15, 1998, not March 15, 1998. This follows the Java 207convention. To avoid mistakes, use the constants defined in the `Calendar` class 208for the months and days of the week. For example, `cal.set(1998, Calendar::APRIL, 15)`.* 209 210#### Ambiguous Wall Clock Time Resolution 211 212When the time offset from UTC has changed, it produces an ambiguous time slot 213around the transition. For example, many US locations observe daylight saving 214time. On the date of transition to daylight saving time in US, wall clock time 215jumps from 12:59 AM (standard) to 2:00 AM (daylight). Therefore, wall clock 216times from 1:00 AM to 1:59 AM do not exist on the date. When the input wall time 217falls into this missing time slot, the ICU Calendar resolves the time using the 218UTC offset before the transition by default. In this example, 1:30 AM is 219interpreted as 1:30 AM standard time (non-exist), so the final result will be 2202:30 AM daylight time. 221On the date of transition back to standard time, wall clock time is moved back 222one hour at 2:00 AM. So wall clock times from 1:00 AM to 1:59 AM occur twice. In 223this case, the ICU Calendar resolves the time using the UTC offset after the 224transition by default. For example, 1:30 AM on the date is resolved as 1:30 AM 225standard time. 226Ambiguous wall clock time resolution behaviors can be customized by Calendar 227APIs `setRepeatedWallTimeOption()` and `setSkippedWallTimeOption()`. These APIs are 228available in ICU 49 or later versions. 229 230### `GregorianCalendar` 231 232The `GregorianCalendar` class implements two calendar systems, the Gregorian 233calendar and the Julian calendar. These calendar systems are closely related, 234differing mainly in their definition of the leap year. The Julian calendar has 235leap years every four years; the Gregorian calendar refines this by excluding 236century years that are not divisible by 400. `GregorianCalendar` defines two eras, 237BC (B.C.E.) and AD (C.E.). 238 239Historically, most western countries used the Julian calendar until the 16th to 24020th century, depending on the country. They then switched to the Gregorian 241calendar. The `GregorianCalendar` class mirrors this behavior by defining a 242cut-over date. Before this date, the Julian calendar algorithms are used. After 243it, the Gregorian calendar algorithms are used. By default, the cut-over date is 244set to October 4, 1582 C.E., which reflects the time when countries first began 245adopting the Gregorian calendar. The `GregorianCalendar` class does not attempt 246historical accuracy beyond this behavior, and does not vary its cut-over date by 247locale. However, users can modify the cut-over date by using the 248`setGregorianChange()` method. 249 250Code that is written correctly instantiates calendar objects using the Calendar 251factory methods, and therefore holds a `Calendar*` pointer. Such code cannot 252directly access the GregorianCalendar-specific methods not present in `Calendar`. 253The correct way to handle this is to perform a dynamic cast, after testing the 254type of the object using `getDynamicClassID()`. For example: 255 256```c++ 257void setCutover(Calendar *cal, UDate myCutover) { 258 if (cal->getDynamicClassID() == GregorianCalendar::getStaticClassID()) { 259 GregorianCalendar *gc = (GregorianCalendar*)cal; 260 gc->setGregorianChange(myCutover, status); 261 } 262} 263``` 264 265> :point_right: **Note**: *This is a general technique that should be used throughout ICU in conjunction 266with the factory methods.* 267 268### Disambiguation 269 270When computing a `UDate` from fields, some special circumstances can arise. There 271might be insufficient information to compute the `UDate` (such as only year and 272month but no day in the month), there might be inconsistent information (such as 273"Tuesday, July 15, 1996" -— July 15, 1996, is actually a Monday), or the input 274time might be ambiguous because of time zone transition. 275 2761. **Insufficient Information** 277 ICU Calendar uses the default field values to specify missing fields. The 278 default for a field is the same as that of the start of the epoch (that is, 279 `YEAR = 1970`, `MONTH = JANUARY`, `DAY_OF_MONTH = 1`). 280 2812. **Inconsistent Information** 282 If fields conflict, the calendar gives preference to fields set more 283 recently. For example, when determining the day, the calendar looks for one 284 of the following combinations of fields: 285 `MONTH + DAY_OF_MONTH` 286 `MONTH + WEEK_OF_MONTH + DAY_OF_WEEK` 287 `MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK` 288 `DAY_OF_YEAR` 289 `DAY_OF_WEEK + WEEK_OF_YEAR` 290 For the time of day, the calendar looks for one of the following 291 combinations of fields: 292 `HOUR_OF_DAY` 293 `AM_PM + HOUR` 294 2953. **Ambiguous Wall Clock Time** 296 When time offset from UTC has changed, it produces ambiguous time slot 297 around the transition. For example, many US locations observe daylight 298 saving time. On the date switching to daylight saving time in US, wall clock 299 time jumps from 1:00 AM (standard) to 2:00 AM (daylight). Therefore, wall 300 clock time from 1:00 AM to 1:59 AM do not exist on the date. When the input 301 wall time fall into this missing time slot, the ICU Calendar resolves the 302 time using the UTC offset before the transition by default. In this example, 303 1:30 AM is interpreted as 1:30 AM standard time (non-exist), so the final 304 result will be 2:30 AM daylight time. 305 On the date switching back to standard time, wall clock time is moved back 306 one hour at 2:00 AM. So wall clock time from 1:00 AM to 1:59 AM occur twice. 307 In this case, the ICU Calendar resolves the time using the UTC offset after 308 the transition by default. For example, 1:30 AM on the date is resolved as 309 1:30 AM standard time. 310 311***Options for Ambiguous Time Resolution*** 312> :point_right: **Note**: *Ambiguous wall clock time resolution behaviors can be customized by Calendar APIs `setRepeatedTimeOption()` and `setSkippedTimeOption()`. These methods are available in ICU 49 or later versions.* 313 314***`WEEK_OF_YEAR` field*** 315> :point_right: **Note**: *Values calculated for the `WEEK_OF_YEAR` field range from 1 to 53. Week 1 for a year is the first week that contains at least `getMinimalDaysInFirstWeek()` days from that year. It depends on the values of `getMinimalDaysInFirstWeek()`, `getFirstDayOfWeek()`, and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (if needed). 316For example, January 1, 1998 was a Thursday. If `getFirstDayOfWeek()` is `MONDAY` 317and `getMinimalDaysInFirstWeek()` is `4` (these are the values reflecting ISO 8601 318and many national standards), then week 1 of 1998 starts on December 29, 1997, 319and ends on January 4, 1998. However, if `getFirstDayOfWeek()` is `SUNDAY`, then 320week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998. The 321first three days of 1998 are then part of week 53 of 1997.* 322 323## Programming Examples 324 325Programming for calendar [examples in C++, C, and Java](examples.md) . 326