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