calendar.cpp 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /*
  4. *******************************************************************************
  5. * Copyright (C) 1997-2016, International Business Machines Corporation and *
  6. * others. All Rights Reserved. *
  7. *******************************************************************************
  8. *
  9. * File CALENDAR.CPP
  10. *
  11. * Modification History:
  12. *
  13. * Date Name Description
  14. * 02/03/97 clhuang Creation.
  15. * 04/22/97 aliu Cleaned up, fixed memory leak, made
  16. * setWeekCountData() more robust.
  17. * Moved platform code to TPlatformUtilities.
  18. * 05/01/97 aliu Made equals(), before(), after() arguments const.
  19. * 05/20/97 aliu Changed logic of when to compute fields and time
  20. * to fix bugs.
  21. * 08/12/97 aliu Added equivalentTo. Misc other fixes.
  22. * 07/28/98 stephen Sync up with JDK 1.2
  23. * 09/02/98 stephen Sync with JDK 1.2 8/31 build (getActualMin/Max)
  24. * 03/17/99 stephen Changed adoptTimeZone() - now fAreFieldsSet is
  25. * set to false to force update of time.
  26. *******************************************************************************
  27. */
  28. #include "utypeinfo.h" // for 'typeid' to work
  29. #include "unicode/utypes.h"
  30. #if !UCONFIG_NO_FORMATTING
  31. #include "unicode/gregocal.h"
  32. #include "unicode/basictz.h"
  33. #include "unicode/simpletz.h"
  34. #include "unicode/rbtz.h"
  35. #include "unicode/vtzone.h"
  36. #include "gregoimp.h"
  37. #include "buddhcal.h"
  38. #include "taiwncal.h"
  39. #include "japancal.h"
  40. #include "islamcal.h"
  41. #include "hebrwcal.h"
  42. #include "persncal.h"
  43. #include "indiancal.h"
  44. #include "iso8601cal.h"
  45. #include "chnsecal.h"
  46. #include "coptccal.h"
  47. #include "dangical.h"
  48. #include "ethpccal.h"
  49. #include "unicode/calendar.h"
  50. #include "cpputils.h"
  51. #include "servloc.h"
  52. #include "ucln_in.h"
  53. #include "cstring.h"
  54. #include "locbased.h"
  55. #include "uresimp.h"
  56. #include "ustrenum.h"
  57. #include "uassert.h"
  58. #include "olsontz.h"
  59. #include "sharedcalendar.h"
  60. #include "unifiedcache.h"
  61. #include "ulocimp.h"
  62. #if !UCONFIG_NO_SERVICE
  63. static icu::ICULocaleService* gService = nullptr;
  64. static icu::UInitOnce gServiceInitOnce {};
  65. // INTERNAL - for cleanup
  66. U_CDECL_BEGIN
  67. static UBool calendar_cleanup() {
  68. #if !UCONFIG_NO_SERVICE
  69. if (gService) {
  70. delete gService;
  71. gService = nullptr;
  72. }
  73. gServiceInitOnce.reset();
  74. #endif
  75. return true;
  76. }
  77. U_CDECL_END
  78. #endif
  79. // ------------------------------------------
  80. //
  81. // Registration
  82. //
  83. //-------------------------------------------
  84. //#define U_DEBUG_CALSVC 1
  85. //
  86. #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
  87. /**
  88. * fldName was removed as a duplicate implementation.
  89. * use udbg_ services instead,
  90. * which depend on include files and library from ../tools/toolutil, the following circular link:
  91. * CPPFLAGS+=-I$(top_srcdir)/tools/toolutil
  92. * LIBS+=$(LIBICUTOOLUTIL)
  93. */
  94. #include "udbgutil.h"
  95. #include <stdio.h>
  96. /**
  97. * convert a UCalendarDateFields into a string - for debugging
  98. * @param f field enum
  99. * @return static string to the field name
  100. * @internal
  101. */
  102. const char* fldName(UCalendarDateFields f) {
  103. return udbg_enumName(UDBG_UCalendarDateFields, (int32_t)f);
  104. }
  105. #if UCAL_DEBUG_DUMP
  106. // from CalendarTest::calToStr - but doesn't modify contents.
  107. void ucal_dump(const Calendar &cal) {
  108. cal.dump();
  109. }
  110. void Calendar::dump() const {
  111. int i;
  112. fprintf(stderr, "@calendar=%s, timeset=%c, fieldset=%c, allfields=%c, virtualset=%c, t=%.2f",
  113. getType(), fIsTimeSet?'y':'n', fAreFieldsSet?'y':'n', fAreAllFieldsSet?'y':'n',
  114. fAreFieldsVirtuallySet?'y':'n',
  115. fTime);
  116. // can add more things here: DST, zone, etc.
  117. fprintf(stderr, "\n");
  118. for(i = 0;i<UCAL_FIELD_COUNT;i++) {
  119. int n;
  120. const char *f = fldName((UCalendarDateFields)i);
  121. fprintf(stderr, " %25s: %-11ld", f, fFields[i]);
  122. if(fStamp[i] == kUnset) {
  123. fprintf(stderr, " (unset) ");
  124. } else if(fStamp[i] == kInternallySet) {
  125. fprintf(stderr, " (internally set) ");
  126. //} else if(fStamp[i] == kInternalDefault) {
  127. // fprintf(stderr, " (internal default) ");
  128. } else {
  129. fprintf(stderr, " %%%d ", fStamp[i]);
  130. }
  131. fprintf(stderr, "\n");
  132. }
  133. }
  134. U_CFUNC void ucal_dump(UCalendar* cal) {
  135. ucal_dump( *((Calendar*)cal) );
  136. }
  137. #endif
  138. #endif
  139. /* Max value for stamp allowable before recalculation */
  140. #define STAMP_MAX 10000
  141. static const char * const gCalTypes[] = {
  142. "gregorian",
  143. "japanese",
  144. "buddhist",
  145. "roc",
  146. "persian",
  147. "islamic-civil",
  148. "islamic",
  149. "hebrew",
  150. "chinese",
  151. "indian",
  152. "coptic",
  153. "ethiopic",
  154. "ethiopic-amete-alem",
  155. "iso8601",
  156. "dangi",
  157. "islamic-umalqura",
  158. "islamic-tbla",
  159. "islamic-rgsa",
  160. nullptr
  161. };
  162. // Must be in the order of gCalTypes above
  163. typedef enum ECalType {
  164. CALTYPE_UNKNOWN = -1,
  165. CALTYPE_GREGORIAN = 0,
  166. CALTYPE_JAPANESE,
  167. CALTYPE_BUDDHIST,
  168. CALTYPE_ROC,
  169. CALTYPE_PERSIAN,
  170. CALTYPE_ISLAMIC_CIVIL,
  171. CALTYPE_ISLAMIC,
  172. CALTYPE_HEBREW,
  173. CALTYPE_CHINESE,
  174. CALTYPE_INDIAN,
  175. CALTYPE_COPTIC,
  176. CALTYPE_ETHIOPIC,
  177. CALTYPE_ETHIOPIC_AMETE_ALEM,
  178. CALTYPE_ISO8601,
  179. CALTYPE_DANGI,
  180. CALTYPE_ISLAMIC_UMALQURA,
  181. CALTYPE_ISLAMIC_TBLA,
  182. CALTYPE_ISLAMIC_RGSA
  183. } ECalType;
  184. U_NAMESPACE_BEGIN
  185. SharedCalendar::~SharedCalendar() {
  186. delete ptr;
  187. }
  188. template<> U_I18N_API
  189. const SharedCalendar *LocaleCacheKey<SharedCalendar>::createObject(
  190. const void * /*unusedCreationContext*/, UErrorCode &status) const {
  191. if (U_FAILURE(status)) {
  192. return nullptr;
  193. }
  194. Calendar *calendar = Calendar::makeInstance(fLoc, status);
  195. if (U_FAILURE(status)) {
  196. return nullptr;
  197. }
  198. SharedCalendar *shared = new SharedCalendar(calendar);
  199. if (shared == nullptr) {
  200. delete calendar;
  201. status = U_MEMORY_ALLOCATION_ERROR;
  202. return nullptr;
  203. }
  204. shared->addRef();
  205. return shared;
  206. }
  207. static ECalType getCalendarType(const char *s) {
  208. for (int i = 0; gCalTypes[i] != nullptr; i++) {
  209. if (uprv_stricmp(s, gCalTypes[i]) == 0) {
  210. return (ECalType)i;
  211. }
  212. }
  213. return CALTYPE_UNKNOWN;
  214. }
  215. #if !UCONFIG_NO_SERVICE
  216. // Only used with service registration.
  217. static UBool isStandardSupportedKeyword(const char *keyword, UErrorCode& status) {
  218. if(U_FAILURE(status)) {
  219. return false;
  220. }
  221. ECalType calType = getCalendarType(keyword);
  222. return (calType != CALTYPE_UNKNOWN);
  223. }
  224. // only used with service registration.
  225. static void getCalendarKeyword(const UnicodeString &id, char *targetBuffer, int32_t targetBufferSize) {
  226. UnicodeString calendarKeyword = UNICODE_STRING_SIMPLE("calendar=");
  227. int32_t calKeyLen = calendarKeyword.length();
  228. int32_t keyLen = 0;
  229. int32_t keywordIdx = id.indexOf((char16_t)0x003D); /* '=' */
  230. if (id[0] == 0x40/*'@'*/
  231. && id.compareBetween(1, keywordIdx+1, calendarKeyword, 0, calKeyLen) == 0)
  232. {
  233. keyLen = id.extract(keywordIdx+1, id.length(), targetBuffer, targetBufferSize, US_INV);
  234. }
  235. targetBuffer[keyLen] = 0;
  236. }
  237. #endif
  238. static ECalType getCalendarTypeForLocale(const char *locid) {
  239. UErrorCode status = U_ZERO_ERROR;
  240. ECalType calType = CALTYPE_UNKNOWN;
  241. //TODO: ULOC_FULL_NAME is out of date and too small..
  242. char canonicalName[256];
  243. // Canonicalize, so that an old-style variant will be transformed to keywords.
  244. // e.g ja_JP_TRADITIONAL -> ja_JP@calendar=japanese
  245. // NOTE: Since ICU-20187, ja_JP_TRADITIONAL no longer canonicalizes, and
  246. // the Gregorian calendar is returned instead.
  247. int32_t canonicalLen = uloc_canonicalize(locid, canonicalName, sizeof(canonicalName) - 1, &status);
  248. if (U_FAILURE(status)) {
  249. return CALTYPE_GREGORIAN;
  250. }
  251. canonicalName[canonicalLen] = 0; // terminate
  252. char calTypeBuf[32];
  253. int32_t calTypeBufLen;
  254. calTypeBufLen = uloc_getKeywordValue(canonicalName, "calendar", calTypeBuf, sizeof(calTypeBuf) - 1, &status);
  255. if (U_SUCCESS(status)) {
  256. calTypeBuf[calTypeBufLen] = 0;
  257. calType = getCalendarType(calTypeBuf);
  258. if (calType != CALTYPE_UNKNOWN) {
  259. return calType;
  260. }
  261. }
  262. status = U_ZERO_ERROR;
  263. // when calendar keyword is not available or not supported, read supplementalData
  264. // to get the default calendar type for the locale's region
  265. char region[ULOC_COUNTRY_CAPACITY];
  266. (void)ulocimp_getRegionForSupplementalData(canonicalName, true, region, sizeof(region), &status);
  267. if (U_FAILURE(status)) {
  268. return CALTYPE_GREGORIAN;
  269. }
  270. // Read preferred calendar values from supplementalData calendarPreference
  271. UResourceBundle *rb = ures_openDirect(nullptr, "supplementalData", &status);
  272. ures_getByKey(rb, "calendarPreferenceData", rb, &status);
  273. UResourceBundle *order = ures_getByKey(rb, region, nullptr, &status);
  274. if (status == U_MISSING_RESOURCE_ERROR && rb != nullptr) {
  275. status = U_ZERO_ERROR;
  276. order = ures_getByKey(rb, "001", nullptr, &status);
  277. }
  278. calTypeBuf[0] = 0;
  279. if (U_SUCCESS(status) && order != nullptr) {
  280. // the first calendar type is the default for the region
  281. int32_t len = 0;
  282. const char16_t *uCalType = ures_getStringByIndex(order, 0, &len, &status);
  283. if (len < (int32_t)sizeof(calTypeBuf)) {
  284. u_UCharsToChars(uCalType, calTypeBuf, len);
  285. *(calTypeBuf + len) = 0; // terminate;
  286. calType = getCalendarType(calTypeBuf);
  287. }
  288. }
  289. ures_close(order);
  290. ures_close(rb);
  291. if (calType == CALTYPE_UNKNOWN) {
  292. // final fallback
  293. calType = CALTYPE_GREGORIAN;
  294. }
  295. return calType;
  296. }
  297. static Calendar *createStandardCalendar(ECalType calType, const Locale &loc, UErrorCode& status) {
  298. if (U_FAILURE(status)) {
  299. return nullptr;
  300. }
  301. LocalPointer<Calendar> cal;
  302. switch (calType) {
  303. case CALTYPE_GREGORIAN:
  304. cal.adoptInsteadAndCheckErrorCode(new GregorianCalendar(loc, status), status);
  305. break;
  306. case CALTYPE_JAPANESE:
  307. cal.adoptInsteadAndCheckErrorCode(new JapaneseCalendar(loc, status), status);
  308. break;
  309. case CALTYPE_BUDDHIST:
  310. cal.adoptInsteadAndCheckErrorCode(new BuddhistCalendar(loc, status), status);
  311. break;
  312. case CALTYPE_ROC:
  313. cal.adoptInsteadAndCheckErrorCode(new TaiwanCalendar(loc, status), status);
  314. break;
  315. case CALTYPE_PERSIAN:
  316. cal.adoptInsteadAndCheckErrorCode(new PersianCalendar(loc, status), status);
  317. break;
  318. case CALTYPE_ISLAMIC_TBLA:
  319. cal.adoptInsteadAndCheckErrorCode(new IslamicTBLACalendar(loc, status), status);
  320. break;
  321. case CALTYPE_ISLAMIC_CIVIL:
  322. cal.adoptInsteadAndCheckErrorCode(new IslamicCivilCalendar(loc, status), status);
  323. break;
  324. case CALTYPE_ISLAMIC_RGSA:
  325. cal.adoptInsteadAndCheckErrorCode(new IslamicRGSACalendar(loc, status), status);
  326. break;
  327. case CALTYPE_ISLAMIC:
  328. cal.adoptInsteadAndCheckErrorCode(new IslamicCalendar(loc, status), status);
  329. break;
  330. case CALTYPE_ISLAMIC_UMALQURA:
  331. cal.adoptInsteadAndCheckErrorCode(new IslamicUmalquraCalendar(loc, status), status);
  332. break;
  333. case CALTYPE_HEBREW:
  334. cal.adoptInsteadAndCheckErrorCode(new HebrewCalendar(loc, status), status);
  335. break;
  336. case CALTYPE_CHINESE:
  337. cal.adoptInsteadAndCheckErrorCode(new ChineseCalendar(loc, status), status);
  338. break;
  339. case CALTYPE_INDIAN:
  340. cal.adoptInsteadAndCheckErrorCode(new IndianCalendar(loc, status), status);
  341. break;
  342. case CALTYPE_COPTIC:
  343. cal.adoptInsteadAndCheckErrorCode(new CopticCalendar(loc, status), status);
  344. break;
  345. case CALTYPE_ETHIOPIC:
  346. cal.adoptInsteadAndCheckErrorCode(new EthiopicCalendar(loc, status), status);
  347. break;
  348. case CALTYPE_ETHIOPIC_AMETE_ALEM:
  349. cal.adoptInsteadAndCheckErrorCode(new EthiopicAmeteAlemCalendar(loc, status), status);
  350. break;
  351. case CALTYPE_ISO8601:
  352. cal.adoptInsteadAndCheckErrorCode(new ISO8601Calendar(loc, status), status);
  353. break;
  354. case CALTYPE_DANGI:
  355. cal.adoptInsteadAndCheckErrorCode(new DangiCalendar(loc, status), status);
  356. break;
  357. default:
  358. status = U_UNSUPPORTED_ERROR;
  359. }
  360. return cal.orphan();
  361. }
  362. #if !UCONFIG_NO_SERVICE
  363. // -------------------------------------
  364. /**
  365. * a Calendar Factory which creates the "basic" calendar types, that is, those
  366. * shipped with ICU.
  367. */
  368. class BasicCalendarFactory : public LocaleKeyFactory {
  369. public:
  370. /**
  371. * @param calendarType static const string (caller owns storage - will be aliased) to calendar type
  372. */
  373. BasicCalendarFactory()
  374. : LocaleKeyFactory(LocaleKeyFactory::INVISIBLE) { }
  375. virtual ~BasicCalendarFactory();
  376. protected:
  377. //virtual UBool isSupportedID( const UnicodeString& id, UErrorCode& status) const {
  378. // if(U_FAILURE(status)) {
  379. // return false;
  380. // }
  381. // char keyword[ULOC_FULLNAME_CAPACITY];
  382. // getCalendarKeyword(id, keyword, (int32_t)sizeof(keyword));
  383. // return isStandardSupportedKeyword(keyword, status);
  384. //}
  385. virtual void updateVisibleIDs(Hashtable& result, UErrorCode& status) const override
  386. {
  387. if (U_SUCCESS(status)) {
  388. for(int32_t i=0;gCalTypes[i] != nullptr;i++) {
  389. UnicodeString id((char16_t)0x40); /* '@' a variant character */
  390. id.append(UNICODE_STRING_SIMPLE("calendar="));
  391. id.append(UnicodeString(gCalTypes[i], -1, US_INV));
  392. result.put(id, (void*)this, status);
  393. }
  394. }
  395. }
  396. virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const override {
  397. if (U_FAILURE(status)) {
  398. return nullptr;
  399. }
  400. #ifdef U_DEBUG_CALSVC
  401. if(dynamic_cast<const LocaleKey*>(&key) == nullptr) {
  402. fprintf(stderr, "::create - not a LocaleKey!\n");
  403. }
  404. #endif
  405. const LocaleKey* lkey = dynamic_cast<const LocaleKey*>(&key);
  406. U_ASSERT(lkey != nullptr);
  407. Locale curLoc; // current locale
  408. Locale canLoc; // Canonical locale
  409. lkey->currentLocale(curLoc);
  410. lkey->canonicalLocale(canLoc);
  411. char keyword[ULOC_FULLNAME_CAPACITY];
  412. UnicodeString str;
  413. key.currentID(str);
  414. getCalendarKeyword(str, keyword, (int32_t) sizeof(keyword));
  415. #ifdef U_DEBUG_CALSVC
  416. fprintf(stderr, "BasicCalendarFactory::create() - cur %s, can %s\n", (const char*)curLoc.getName(), (const char*)canLoc.getName());
  417. #endif
  418. if(!isStandardSupportedKeyword(keyword,status)) { // Do we handle this type?
  419. #ifdef U_DEBUG_CALSVC
  420. fprintf(stderr, "BasicCalendarFactory - not handling %s.[%s]\n", (const char*) curLoc.getName(), tmp );
  421. #endif
  422. return nullptr;
  423. }
  424. return createStandardCalendar(getCalendarType(keyword), canLoc, status);
  425. }
  426. };
  427. BasicCalendarFactory::~BasicCalendarFactory() {}
  428. /**
  429. * A factory which looks up the DefaultCalendar resource to determine which class of calendar to use
  430. */
  431. class DefaultCalendarFactory : public ICUResourceBundleFactory {
  432. public:
  433. DefaultCalendarFactory() : ICUResourceBundleFactory() { }
  434. virtual ~DefaultCalendarFactory();
  435. protected:
  436. virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const override {
  437. if (U_FAILURE(status)) {
  438. return nullptr;
  439. }
  440. const LocaleKey *lkey = dynamic_cast<const LocaleKey*>(&key);
  441. U_ASSERT(lkey != nullptr);
  442. Locale loc;
  443. lkey->currentLocale(loc);
  444. UnicodeString *ret = new UnicodeString();
  445. if (ret == nullptr) {
  446. status = U_MEMORY_ALLOCATION_ERROR;
  447. } else {
  448. ret->append((char16_t)0x40); // '@' is a variant character
  449. ret->append(UNICODE_STRING("calendar=", 9));
  450. ret->append(UnicodeString(gCalTypes[getCalendarTypeForLocale(loc.getName())], -1, US_INV));
  451. }
  452. return ret;
  453. }
  454. };
  455. DefaultCalendarFactory::~DefaultCalendarFactory() {}
  456. // -------------------------------------
  457. class CalendarService : public ICULocaleService {
  458. public:
  459. CalendarService()
  460. : ICULocaleService(UNICODE_STRING_SIMPLE("Calendar"))
  461. {
  462. UErrorCode status = U_ZERO_ERROR;
  463. registerFactory(new DefaultCalendarFactory(), status);
  464. }
  465. virtual ~CalendarService();
  466. virtual UObject* cloneInstance(UObject* instance) const override {
  467. UnicodeString *s = dynamic_cast<UnicodeString *>(instance);
  468. if(s != nullptr) {
  469. return s->clone();
  470. } else {
  471. #ifdef U_DEBUG_CALSVC_F
  472. UErrorCode status2 = U_ZERO_ERROR;
  473. fprintf(stderr, "Cloning a %s calendar with tz=%ld\n", ((Calendar*)instance)->getType(), ((Calendar*)instance)->get(UCAL_ZONE_OFFSET, status2));
  474. #endif
  475. return ((Calendar*)instance)->clone();
  476. }
  477. }
  478. virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* /*actualID*/, UErrorCode& status) const override {
  479. if (U_FAILURE(status)) {
  480. return nullptr;
  481. }
  482. LocaleKey& lkey = static_cast<LocaleKey&>(const_cast<ICUServiceKey&>(key));
  483. //int32_t kind = lkey.kind();
  484. Locale loc;
  485. lkey.canonicalLocale(loc);
  486. #ifdef U_DEBUG_CALSVC
  487. Locale loc2;
  488. lkey.currentLocale(loc2);
  489. fprintf(stderr, "CalSvc:handleDefault for currentLoc %s, canloc %s\n", (const char*)loc.getName(), (const char*)loc2.getName());
  490. #endif
  491. Calendar *nc = new GregorianCalendar(loc, status);
  492. if (nc == nullptr) {
  493. status = U_MEMORY_ALLOCATION_ERROR;
  494. return nc;
  495. }
  496. #ifdef U_DEBUG_CALSVC
  497. UErrorCode status2 = U_ZERO_ERROR;
  498. fprintf(stderr, "New default calendar has tz=%d\n", ((Calendar*)nc)->get(UCAL_ZONE_OFFSET, status2));
  499. #endif
  500. return nc;
  501. }
  502. virtual UBool isDefault() const override {
  503. return countFactories() == 1;
  504. }
  505. };
  506. CalendarService::~CalendarService() {}
  507. // -------------------------------------
  508. static inline UBool
  509. isCalendarServiceUsed() {
  510. return !gServiceInitOnce.isReset();
  511. }
  512. // -------------------------------------
  513. static void U_CALLCONV
  514. initCalendarService(UErrorCode &status)
  515. {
  516. #ifdef U_DEBUG_CALSVC
  517. fprintf(stderr, "Spinning up Calendar Service\n");
  518. #endif
  519. if (U_FAILURE(status)) {
  520. return;
  521. }
  522. ucln_i18n_registerCleanup(UCLN_I18N_CALENDAR, calendar_cleanup);
  523. gService = new CalendarService();
  524. if (gService == nullptr) {
  525. status = U_MEMORY_ALLOCATION_ERROR;
  526. return;
  527. }
  528. #ifdef U_DEBUG_CALSVC
  529. fprintf(stderr, "Registering classes..\n");
  530. #endif
  531. // Register all basic instances.
  532. gService->registerFactory(new BasicCalendarFactory(),status);
  533. #ifdef U_DEBUG_CALSVC
  534. fprintf(stderr, "Done..\n");
  535. #endif
  536. if(U_FAILURE(status)) {
  537. #ifdef U_DEBUG_CALSVC
  538. fprintf(stderr, "err (%s) registering classes, deleting service.....\n", u_errorName(status));
  539. #endif
  540. delete gService;
  541. gService = nullptr;
  542. }
  543. }
  544. static ICULocaleService*
  545. getCalendarService(UErrorCode &status)
  546. {
  547. umtx_initOnce(gServiceInitOnce, &initCalendarService, status);
  548. return gService;
  549. }
  550. URegistryKey Calendar::registerFactory(ICUServiceFactory* toAdopt, UErrorCode& status)
  551. {
  552. return getCalendarService(status)->registerFactory(toAdopt, status);
  553. }
  554. UBool Calendar::unregister(URegistryKey key, UErrorCode& status) {
  555. return getCalendarService(status)->unregister(key, status);
  556. }
  557. #endif /* UCONFIG_NO_SERVICE */
  558. // -------------------------------------
  559. static const int32_t kCalendarLimits[UCAL_FIELD_COUNT][4] = {
  560. // Minimum Greatest min Least max Greatest max
  561. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // ERA
  562. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR
  563. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // MONTH
  564. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_YEAR
  565. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_MONTH
  566. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_MONTH
  567. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_YEAR
  568. { 1, 1, 7, 7 }, // DAY_OF_WEEK
  569. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_WEEK_IN_MONTH
  570. { 0, 0, 1, 1 }, // AM_PM
  571. { 0, 0, 11, 11 }, // HOUR
  572. { 0, 0, 23, 23 }, // HOUR_OF_DAY
  573. { 0, 0, 59, 59 }, // MINUTE
  574. { 0, 0, 59, 59 }, // SECOND
  575. { 0, 0, 999, 999 }, // MILLISECOND
  576. {-16*kOneHour, -16*kOneHour, 12*kOneHour, 30*kOneHour }, // ZONE_OFFSET
  577. { -1*kOneHour, -1*kOneHour, 2*kOneHour, 2*kOneHour }, // DST_OFFSET
  578. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR_WOY
  579. { 1, 1, 7, 7 }, // DOW_LOCAL
  580. {/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // EXTENDED_YEAR
  581. { -0x7F000000, -0x7F000000, 0x7F000000, 0x7F000000 }, // JULIAN_DAY
  582. { 0, 0, 24*kOneHour-1, 24*kOneHour-1 }, // MILLISECONDS_IN_DAY
  583. { 0, 0, 1, 1 }, // IS_LEAP_MONTH
  584. { 0, 0, 11, 11 } // ORDINAL_MONTH
  585. };
  586. // Resource bundle tags read by this class
  587. static const char gCalendar[] = "calendar";
  588. static const char gMonthNames[] = "monthNames";
  589. static const char gGregorian[] = "gregorian";
  590. // Data flow in Calendar
  591. // ---------------------
  592. // The current time is represented in two ways by Calendar: as UTC
  593. // milliseconds from the epoch start (1 January 1970 0:00 UTC), and as local
  594. // fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
  595. // millis from the fields, and vice versa. The data needed to do this
  596. // conversion is encapsulated by a TimeZone object owned by the Calendar.
  597. // The data provided by the TimeZone object may also be overridden if the
  598. // user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
  599. // keeps track of what information was most recently set by the caller, and
  600. // uses that to compute any other information as needed.
  601. // If the user sets the fields using set(), the data flow is as follows.
  602. // This is implemented by the Calendar subclass's computeTime() method.
  603. // During this process, certain fields may be ignored. The disambiguation
  604. // algorithm for resolving which fields to pay attention to is described
  605. // above.
  606. // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
  607. // |
  608. // | Using Calendar-specific algorithm
  609. // V
  610. // local standard millis
  611. // |
  612. // | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
  613. // V
  614. // UTC millis (in time data member)
  615. // If the user sets the UTC millis using setTime(), the data flow is as
  616. // follows. This is implemented by the Calendar subclass's computeFields()
  617. // method.
  618. // UTC millis (in time data member)
  619. // |
  620. // | Using TimeZone getOffset()
  621. // V
  622. // local standard millis
  623. // |
  624. // | Using Calendar-specific algorithm
  625. // V
  626. // local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
  627. // In general, a round trip from fields, through local and UTC millis, and
  628. // back out to fields is made when necessary. This is implemented by the
  629. // complete() method. Resolving a partial set of fields into a UTC millis
  630. // value allows all remaining fields to be generated from that value. If
  631. // the Calendar is lenient, the fields are also renormalized to standard
  632. // ranges when they are regenerated.
  633. // -------------------------------------
  634. Calendar::Calendar(UErrorCode& success)
  635. : UObject(),
  636. fIsTimeSet(false),
  637. fAreFieldsSet(false),
  638. fAreAllFieldsSet(false),
  639. fAreFieldsVirtuallySet(false),
  640. fNextStamp((int32_t)kMinimumUserStamp),
  641. fTime(0),
  642. fLenient(true),
  643. fZone(nullptr),
  644. fRepeatedWallTime(UCAL_WALLTIME_LAST),
  645. fSkippedWallTime(UCAL_WALLTIME_LAST)
  646. {
  647. validLocale[0] = 0;
  648. actualLocale[0] = 0;
  649. clear();
  650. if (U_FAILURE(success)) {
  651. return;
  652. }
  653. fZone = TimeZone::createDefault();
  654. if (fZone == nullptr) {
  655. success = U_MEMORY_ALLOCATION_ERROR;
  656. }
  657. setWeekData(Locale::getDefault(), nullptr, success);
  658. }
  659. // -------------------------------------
  660. Calendar::Calendar(TimeZone* zone, const Locale& aLocale, UErrorCode& success)
  661. : UObject(),
  662. fIsTimeSet(false),
  663. fAreFieldsSet(false),
  664. fAreAllFieldsSet(false),
  665. fAreFieldsVirtuallySet(false),
  666. fNextStamp((int32_t)kMinimumUserStamp),
  667. fTime(0),
  668. fLenient(true),
  669. fZone(nullptr),
  670. fRepeatedWallTime(UCAL_WALLTIME_LAST),
  671. fSkippedWallTime(UCAL_WALLTIME_LAST)
  672. {
  673. validLocale[0] = 0;
  674. actualLocale[0] = 0;
  675. if (U_FAILURE(success)) {
  676. delete zone;
  677. return;
  678. }
  679. if(zone == 0) {
  680. #if defined (U_DEBUG_CAL)
  681. fprintf(stderr, "%s:%d: ILLEGAL ARG because timezone cannot be 0\n",
  682. __FILE__, __LINE__);
  683. #endif
  684. success = U_ILLEGAL_ARGUMENT_ERROR;
  685. return;
  686. }
  687. clear();
  688. fZone = zone;
  689. setWeekData(aLocale, nullptr, success);
  690. }
  691. // -------------------------------------
  692. Calendar::Calendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success)
  693. : UObject(),
  694. fIsTimeSet(false),
  695. fAreFieldsSet(false),
  696. fAreAllFieldsSet(false),
  697. fAreFieldsVirtuallySet(false),
  698. fNextStamp((int32_t)kMinimumUserStamp),
  699. fTime(0),
  700. fLenient(true),
  701. fZone(nullptr),
  702. fRepeatedWallTime(UCAL_WALLTIME_LAST),
  703. fSkippedWallTime(UCAL_WALLTIME_LAST)
  704. {
  705. validLocale[0] = 0;
  706. actualLocale[0] = 0;
  707. if (U_FAILURE(success)) {
  708. return;
  709. }
  710. clear();
  711. fZone = zone.clone();
  712. if (fZone == nullptr) {
  713. success = U_MEMORY_ALLOCATION_ERROR;
  714. }
  715. setWeekData(aLocale, nullptr, success);
  716. }
  717. // -------------------------------------
  718. Calendar::~Calendar()
  719. {
  720. delete fZone;
  721. }
  722. // -------------------------------------
  723. Calendar::Calendar(const Calendar &source)
  724. : UObject(source)
  725. {
  726. fZone = nullptr;
  727. *this = source;
  728. }
  729. // -------------------------------------
  730. Calendar &
  731. Calendar::operator=(const Calendar &right)
  732. {
  733. if (this != &right) {
  734. uprv_arrayCopy(right.fFields, fFields, UCAL_FIELD_COUNT);
  735. uprv_arrayCopy(right.fIsSet, fIsSet, UCAL_FIELD_COUNT);
  736. uprv_arrayCopy(right.fStamp, fStamp, UCAL_FIELD_COUNT);
  737. fTime = right.fTime;
  738. fIsTimeSet = right.fIsTimeSet;
  739. fAreAllFieldsSet = right.fAreAllFieldsSet;
  740. fAreFieldsSet = right.fAreFieldsSet;
  741. fAreFieldsVirtuallySet = right.fAreFieldsVirtuallySet;
  742. fLenient = right.fLenient;
  743. fRepeatedWallTime = right.fRepeatedWallTime;
  744. fSkippedWallTime = right.fSkippedWallTime;
  745. delete fZone;
  746. fZone = nullptr;
  747. if (right.fZone != nullptr) {
  748. fZone = right.fZone->clone();
  749. }
  750. fFirstDayOfWeek = right.fFirstDayOfWeek;
  751. fMinimalDaysInFirstWeek = right.fMinimalDaysInFirstWeek;
  752. fWeekendOnset = right.fWeekendOnset;
  753. fWeekendOnsetMillis = right.fWeekendOnsetMillis;
  754. fWeekendCease = right.fWeekendCease;
  755. fWeekendCeaseMillis = right.fWeekendCeaseMillis;
  756. fNextStamp = right.fNextStamp;
  757. uprv_strncpy(validLocale, right.validLocale, sizeof(validLocale));
  758. uprv_strncpy(actualLocale, right.actualLocale, sizeof(actualLocale));
  759. validLocale[sizeof(validLocale)-1] = 0;
  760. actualLocale[sizeof(validLocale)-1] = 0;
  761. }
  762. return *this;
  763. }
  764. // -------------------------------------
  765. Calendar* U_EXPORT2
  766. Calendar::createInstance(UErrorCode& success)
  767. {
  768. return createInstance(TimeZone::createDefault(), Locale::getDefault(), success);
  769. }
  770. // -------------------------------------
  771. Calendar* U_EXPORT2
  772. Calendar::createInstance(const TimeZone& zone, UErrorCode& success)
  773. {
  774. return createInstance(zone, Locale::getDefault(), success);
  775. }
  776. // -------------------------------------
  777. Calendar* U_EXPORT2
  778. Calendar::createInstance(const Locale& aLocale, UErrorCode& success)
  779. {
  780. return createInstance(TimeZone::forLocaleOrDefault(aLocale), aLocale, success);
  781. }
  782. // ------------------------------------- Adopting
  783. // Note: this is the bottleneck that actually calls the service routines.
  784. Calendar * U_EXPORT2
  785. Calendar::makeInstance(const Locale& aLocale, UErrorCode& success) {
  786. if (U_FAILURE(success)) {
  787. return nullptr;
  788. }
  789. Locale actualLoc;
  790. UObject* u = nullptr;
  791. #if !UCONFIG_NO_SERVICE
  792. if (isCalendarServiceUsed()) {
  793. u = getCalendarService(success)->get(aLocale, LocaleKey::KIND_ANY, &actualLoc, success);
  794. }
  795. else
  796. #endif
  797. {
  798. u = createStandardCalendar(getCalendarTypeForLocale(aLocale.getName()), aLocale, success);
  799. }
  800. Calendar* c = nullptr;
  801. if(U_FAILURE(success) || !u) {
  802. if(U_SUCCESS(success)) { // Propagate some kind of err
  803. success = U_INTERNAL_PROGRAM_ERROR;
  804. }
  805. return nullptr;
  806. }
  807. #if !UCONFIG_NO_SERVICE
  808. const UnicodeString* str = dynamic_cast<const UnicodeString*>(u);
  809. if(str != nullptr) {
  810. // It's a unicode string telling us what type of calendar to load ("gregorian", etc)
  811. // Create a Locale over this string
  812. Locale l("");
  813. LocaleUtility::initLocaleFromName(*str, l);
  814. #ifdef U_DEBUG_CALSVC
  815. fprintf(stderr, "Calendar::createInstance(%s), looking up [%s]\n", aLocale.getName(), l.getName());
  816. #endif
  817. Locale actualLoc2;
  818. delete u;
  819. u = nullptr;
  820. // Don't overwrite actualLoc, since the actual loc from this call
  821. // may be something like "@calendar=gregorian" -- TODO investigate
  822. // further...
  823. c = (Calendar*)getCalendarService(success)->get(l, LocaleKey::KIND_ANY, &actualLoc2, success);
  824. if(U_FAILURE(success) || !c) {
  825. if(U_SUCCESS(success)) {
  826. success = U_INTERNAL_PROGRAM_ERROR; // Propagate some err
  827. }
  828. return nullptr;
  829. }
  830. str = dynamic_cast<const UnicodeString*>(c);
  831. if(str != nullptr) {
  832. // recursed! Second lookup returned a UnicodeString.
  833. // Perhaps DefaultCalendar{} was set to another locale.
  834. #ifdef U_DEBUG_CALSVC
  835. char tmp[200];
  836. // Extract a char* out of it..
  837. int32_t len = str->length();
  838. int32_t actLen = sizeof(tmp)-1;
  839. if(len > actLen) {
  840. len = actLen;
  841. }
  842. str->extract(0,len,tmp);
  843. tmp[len]=0;
  844. fprintf(stderr, "err - recursed, 2nd lookup was unistring %s\n", tmp);
  845. #endif
  846. success = U_MISSING_RESOURCE_ERROR; // requested a calendar type which could NOT be found.
  847. delete c;
  848. return nullptr;
  849. }
  850. #ifdef U_DEBUG_CALSVC
  851. fprintf(stderr, "%p: setting week count data to locale %s, actual locale %s\n", c, (const char*)aLocale.getName(), (const char *)actualLoc.getName());
  852. #endif
  853. c->setWeekData(aLocale, c->getType(), success); // set the correct locale (this was an indirect calendar)
  854. char keyword[ULOC_FULLNAME_CAPACITY] = "";
  855. UErrorCode tmpStatus = U_ZERO_ERROR;
  856. l.getKeywordValue("calendar", keyword, ULOC_FULLNAME_CAPACITY, tmpStatus);
  857. if (U_SUCCESS(tmpStatus) && uprv_strcmp(keyword, "iso8601") == 0) {
  858. c->setFirstDayOfWeek(UCAL_MONDAY);
  859. c->setMinimalDaysInFirstWeek(4);
  860. }
  861. }
  862. else
  863. #endif /* UCONFIG_NO_SERVICE */
  864. {
  865. // a calendar was returned - we assume the factory did the right thing.
  866. c = (Calendar*)u;
  867. }
  868. return c;
  869. }
  870. Calendar* U_EXPORT2
  871. Calendar::createInstance(TimeZone* zone, const Locale& aLocale, UErrorCode& success)
  872. {
  873. LocalPointer<TimeZone> zonePtr(zone);
  874. const SharedCalendar *shared = nullptr;
  875. UnifiedCache::getByLocale(aLocale, shared, success);
  876. if (U_FAILURE(success)) {
  877. return nullptr;
  878. }
  879. Calendar *c = (*shared)->clone();
  880. shared->removeRef();
  881. if (c == nullptr) {
  882. success = U_MEMORY_ALLOCATION_ERROR;
  883. return nullptr;
  884. }
  885. // Now, reset calendar to default state:
  886. c->adoptTimeZone(zonePtr.orphan()); // Set the correct time zone
  887. c->setTimeInMillis(getNow(), success); // let the new calendar have the current time.
  888. return c;
  889. }
  890. // -------------------------------------
  891. Calendar* U_EXPORT2
  892. Calendar::createInstance(const TimeZone& zone, const Locale& aLocale, UErrorCode& success)
  893. {
  894. Calendar* c = createInstance(aLocale, success);
  895. if(U_SUCCESS(success) && c) {
  896. c->setTimeZone(zone);
  897. }
  898. return c;
  899. }
  900. // -------------------------------------
  901. void U_EXPORT2
  902. Calendar::getCalendarTypeFromLocale(
  903. const Locale &aLocale,
  904. char *typeBuffer,
  905. int32_t typeBufferSize,
  906. UErrorCode &success) {
  907. const SharedCalendar *shared = nullptr;
  908. UnifiedCache::getByLocale(aLocale, shared, success);
  909. if (U_FAILURE(success)) {
  910. return;
  911. }
  912. uprv_strncpy(typeBuffer, (*shared)->getType(), typeBufferSize);
  913. shared->removeRef();
  914. if (typeBuffer[typeBufferSize - 1]) {
  915. success = U_BUFFER_OVERFLOW_ERROR;
  916. }
  917. }
  918. bool
  919. Calendar::operator==(const Calendar& that) const
  920. {
  921. UErrorCode status = U_ZERO_ERROR;
  922. return isEquivalentTo(that) &&
  923. getTimeInMillis(status) == that.getTimeInMillis(status) &&
  924. U_SUCCESS(status);
  925. }
  926. UBool
  927. Calendar::isEquivalentTo(const Calendar& other) const
  928. {
  929. return typeid(*this) == typeid(other) &&
  930. fLenient == other.fLenient &&
  931. fRepeatedWallTime == other.fRepeatedWallTime &&
  932. fSkippedWallTime == other.fSkippedWallTime &&
  933. fFirstDayOfWeek == other.fFirstDayOfWeek &&
  934. fMinimalDaysInFirstWeek == other.fMinimalDaysInFirstWeek &&
  935. fWeekendOnset == other.fWeekendOnset &&
  936. fWeekendOnsetMillis == other.fWeekendOnsetMillis &&
  937. fWeekendCease == other.fWeekendCease &&
  938. fWeekendCeaseMillis == other.fWeekendCeaseMillis &&
  939. *fZone == *other.fZone;
  940. }
  941. // -------------------------------------
  942. UBool
  943. Calendar::equals(const Calendar& when, UErrorCode& status) const
  944. {
  945. return (this == &when ||
  946. getTime(status) == when.getTime(status));
  947. }
  948. // -------------------------------------
  949. UBool
  950. Calendar::before(const Calendar& when, UErrorCode& status) const
  951. {
  952. return (this != &when &&
  953. getTimeInMillis(status) < when.getTimeInMillis(status));
  954. }
  955. // -------------------------------------
  956. UBool
  957. Calendar::after(const Calendar& when, UErrorCode& status) const
  958. {
  959. return (this != &when &&
  960. getTimeInMillis(status) > when.getTimeInMillis(status));
  961. }
  962. // -------------------------------------
  963. const Locale* U_EXPORT2
  964. Calendar::getAvailableLocales(int32_t& count)
  965. {
  966. return Locale::getAvailableLocales(count);
  967. }
  968. // -------------------------------------
  969. StringEnumeration* U_EXPORT2
  970. Calendar::getKeywordValuesForLocale(const char* key,
  971. const Locale& locale, UBool commonlyUsed, UErrorCode& status)
  972. {
  973. // This is a wrapper over ucal_getKeywordValuesForLocale
  974. UEnumeration *uenum = ucal_getKeywordValuesForLocale(key, locale.getName(),
  975. commonlyUsed, &status);
  976. if (U_FAILURE(status)) {
  977. uenum_close(uenum);
  978. return nullptr;
  979. }
  980. UStringEnumeration* ustringenum = new UStringEnumeration(uenum);
  981. if (ustringenum == nullptr) {
  982. status = U_MEMORY_ALLOCATION_ERROR;
  983. }
  984. return ustringenum;
  985. }
  986. // -------------------------------------
  987. UDate U_EXPORT2
  988. Calendar::getNow()
  989. {
  990. return uprv_getUTCtime(); // return as milliseconds
  991. }
  992. // -------------------------------------
  993. /**
  994. * Gets this Calendar's current time as a long.
  995. * @return the current time as UTC milliseconds from the epoch.
  996. */
  997. double
  998. Calendar::getTimeInMillis(UErrorCode& status) const
  999. {
  1000. if(U_FAILURE(status))
  1001. return 0.0;
  1002. if ( ! fIsTimeSet)
  1003. ((Calendar*)this)->updateTime(status);
  1004. /* Test for buffer overflows */
  1005. if(U_FAILURE(status)) {
  1006. return 0.0;
  1007. }
  1008. return fTime;
  1009. }
  1010. // -------------------------------------
  1011. /**
  1012. * Sets this Calendar's current time from the given long value.
  1013. * A status of U_ILLEGAL_ARGUMENT_ERROR is set when millis is
  1014. * outside the range permitted by a Calendar object when not in lenient mode.
  1015. * when in lenient mode the out of range values are pinned to their respective min/max.
  1016. * @param date the new time in UTC milliseconds from the epoch.
  1017. */
  1018. void
  1019. Calendar::setTimeInMillis( double millis, UErrorCode& status ) {
  1020. if(U_FAILURE(status))
  1021. return;
  1022. if (millis > MAX_MILLIS) {
  1023. if(isLenient()) {
  1024. millis = MAX_MILLIS;
  1025. } else {
  1026. status = U_ILLEGAL_ARGUMENT_ERROR;
  1027. return;
  1028. }
  1029. } else if (millis < MIN_MILLIS) {
  1030. if(isLenient()) {
  1031. millis = MIN_MILLIS;
  1032. } else {
  1033. status = U_ILLEGAL_ARGUMENT_ERROR;
  1034. return;
  1035. }
  1036. }
  1037. fTime = millis;
  1038. fAreFieldsSet = fAreAllFieldsSet = false;
  1039. fIsTimeSet = fAreFieldsVirtuallySet = true;
  1040. for (int32_t i=0; i<UCAL_FIELD_COUNT; ++i) {
  1041. fFields[i] = 0;
  1042. fStamp[i] = kUnset;
  1043. fIsSet[i] = false;
  1044. }
  1045. }
  1046. // -------------------------------------
  1047. int32_t
  1048. Calendar::get(UCalendarDateFields field, UErrorCode& status) const
  1049. {
  1050. // field values are only computed when actually requested; for more on when computation
  1051. // of various things happens, see the "data flow in Calendar" description at the top
  1052. // of this file
  1053. if (U_SUCCESS(status)) ((Calendar*)this)->complete(status); // Cast away const
  1054. return U_SUCCESS(status) ? fFields[field] : 0;
  1055. }
  1056. // -------------------------------------
  1057. void
  1058. Calendar::set(UCalendarDateFields field, int32_t value)
  1059. {
  1060. if (fAreFieldsVirtuallySet) {
  1061. UErrorCode ec = U_ZERO_ERROR;
  1062. computeFields(ec);
  1063. }
  1064. fFields[field] = value;
  1065. /* Ensure that the fNextStamp value doesn't go pass max value for int32_t */
  1066. if (fNextStamp == STAMP_MAX) {
  1067. recalculateStamp();
  1068. }
  1069. fStamp[field] = fNextStamp++;
  1070. fIsSet[field] = true; // Remove later
  1071. fIsTimeSet = fAreFieldsSet = fAreFieldsVirtuallySet = false;
  1072. }
  1073. // -------------------------------------
  1074. void
  1075. Calendar::set(int32_t year, int32_t month, int32_t date)
  1076. {
  1077. set(UCAL_YEAR, year);
  1078. set(UCAL_MONTH, month);
  1079. set(UCAL_DATE, date);
  1080. }
  1081. // -------------------------------------
  1082. void
  1083. Calendar::set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute)
  1084. {
  1085. set(UCAL_YEAR, year);
  1086. set(UCAL_MONTH, month);
  1087. set(UCAL_DATE, date);
  1088. set(UCAL_HOUR_OF_DAY, hour);
  1089. set(UCAL_MINUTE, minute);
  1090. }
  1091. // -------------------------------------
  1092. void
  1093. Calendar::set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second)
  1094. {
  1095. set(UCAL_YEAR, year);
  1096. set(UCAL_MONTH, month);
  1097. set(UCAL_DATE, date);
  1098. set(UCAL_HOUR_OF_DAY, hour);
  1099. set(UCAL_MINUTE, minute);
  1100. set(UCAL_SECOND, second);
  1101. }
  1102. // -------------------------------------
  1103. int32_t Calendar::getRelatedYear(UErrorCode &status) const
  1104. {
  1105. return get(UCAL_EXTENDED_YEAR, status);
  1106. }
  1107. // -------------------------------------
  1108. void Calendar::setRelatedYear(int32_t year)
  1109. {
  1110. // set extended year
  1111. set(UCAL_EXTENDED_YEAR, year);
  1112. }
  1113. // -------------------------------------
  1114. void
  1115. Calendar::clear()
  1116. {
  1117. for (int32_t i=0; i<UCAL_FIELD_COUNT; ++i) {
  1118. fFields[i] = 0; // Must do this; other code depends on it
  1119. fStamp[i] = kUnset;
  1120. fIsSet[i] = false; // Remove later
  1121. }
  1122. fIsTimeSet = fAreFieldsSet = fAreAllFieldsSet = fAreFieldsVirtuallySet = false;
  1123. // fTime is not 'cleared' - may be used if no fields are set.
  1124. }
  1125. // -------------------------------------
  1126. void
  1127. Calendar::clear(UCalendarDateFields field)
  1128. {
  1129. if (fAreFieldsVirtuallySet) {
  1130. UErrorCode ec = U_ZERO_ERROR;
  1131. computeFields(ec);
  1132. }
  1133. fFields[field] = 0;
  1134. fStamp[field] = kUnset;
  1135. fIsSet[field] = false; // Remove later
  1136. fIsTimeSet = fAreFieldsSet = fAreAllFieldsSet = fAreFieldsVirtuallySet = false;
  1137. }
  1138. // -------------------------------------
  1139. UBool
  1140. Calendar::isSet(UCalendarDateFields field) const
  1141. {
  1142. return fAreFieldsVirtuallySet || (fStamp[field] != kUnset);
  1143. }
  1144. int32_t Calendar::newestStamp(UCalendarDateFields first, UCalendarDateFields last, int32_t bestStampSoFar) const
  1145. {
  1146. int32_t bestStamp = bestStampSoFar;
  1147. for (int32_t i=(int32_t)first; i<=(int32_t)last; ++i) {
  1148. if (fStamp[i] > bestStamp) {
  1149. bestStamp = fStamp[i];
  1150. }
  1151. }
  1152. return bestStamp;
  1153. }
  1154. // -------------------------------------
  1155. void
  1156. Calendar::complete(UErrorCode& status)
  1157. {
  1158. if (U_FAILURE(status)) {
  1159. return;
  1160. }
  1161. if (!fIsTimeSet) {
  1162. updateTime(status);
  1163. /* Test for buffer overflows */
  1164. if(U_FAILURE(status)) {
  1165. return;
  1166. }
  1167. }
  1168. if (!fAreFieldsSet) {
  1169. computeFields(status); // fills in unset fields
  1170. /* Test for buffer overflows */
  1171. if(U_FAILURE(status)) {
  1172. return;
  1173. }
  1174. fAreFieldsSet = true;
  1175. fAreAllFieldsSet = true;
  1176. }
  1177. }
  1178. //-------------------------------------------------------------------------
  1179. // Protected utility methods for use by subclasses. These are very handy
  1180. // for implementing add, roll, and computeFields.
  1181. //-------------------------------------------------------------------------
  1182. /**
  1183. * Adjust the specified field so that it is within
  1184. * the allowable range for the date to which this calendar is set.
  1185. * For example, in a Gregorian calendar pinning the {@link #DAY_OF_MONTH DAY_OF_MONTH}
  1186. * field for a calendar set to April 31 would cause it to be set
  1187. * to April 30.
  1188. * <p>
  1189. * <b>Subclassing:</b>
  1190. * <br>
  1191. * This utility method is intended for use by subclasses that need to implement
  1192. * their own overrides of {@link #roll roll} and {@link #add add}.
  1193. * <p>
  1194. * <b>Note:</b>
  1195. * <code>pinField</code> is implemented in terms of
  1196. * {@link #getActualMinimum getActualMinimum}
  1197. * and {@link #getActualMaximum getActualMaximum}. If either of those methods uses
  1198. * a slow, iterative algorithm for a particular field, it would be
  1199. * unwise to attempt to call <code>pinField</code> for that field. If you
  1200. * really do need to do so, you should override this method to do
  1201. * something more efficient for that field.
  1202. * <p>
  1203. * @param field The calendar field whose value should be pinned.
  1204. *
  1205. * @see #getActualMinimum
  1206. * @see #getActualMaximum
  1207. * @stable ICU 2.0
  1208. */
  1209. void Calendar::pinField(UCalendarDateFields field, UErrorCode& status) {
  1210. if (U_FAILURE(status)) {
  1211. return;
  1212. }
  1213. int32_t max = getActualMaximum(field, status);
  1214. int32_t min = getActualMinimum(field, status);
  1215. if (fFields[field] > max) {
  1216. set(field, max);
  1217. } else if (fFields[field] < min) {
  1218. set(field, min);
  1219. }
  1220. }
  1221. void Calendar::computeFields(UErrorCode &ec)
  1222. {
  1223. if (U_FAILURE(ec)) {
  1224. return;
  1225. }
  1226. // Compute local wall millis
  1227. double localMillis = internalGetTime();
  1228. int32_t rawOffset, dstOffset;
  1229. getTimeZone().getOffset(localMillis, false, rawOffset, dstOffset, ec);
  1230. if (U_FAILURE(ec)) {
  1231. return;
  1232. }
  1233. localMillis += (rawOffset + dstOffset);
  1234. // Mark fields as set. Do this before calling handleComputeFields().
  1235. uint32_t mask = //fInternalSetMask;
  1236. (1 << UCAL_ERA) |
  1237. (1 << UCAL_YEAR) |
  1238. (1 << UCAL_MONTH) |
  1239. (1 << UCAL_DAY_OF_MONTH) | // = UCAL_DATE
  1240. (1 << UCAL_DAY_OF_YEAR) |
  1241. (1 << UCAL_EXTENDED_YEAR) |
  1242. (1 << UCAL_ORDINAL_MONTH);
  1243. for (int32_t i=0; i<UCAL_FIELD_COUNT; ++i) {
  1244. if ((mask & 1) == 0) {
  1245. fStamp[i] = kInternallySet;
  1246. fIsSet[i] = true; // Remove later
  1247. } else {
  1248. fStamp[i] = kUnset;
  1249. fIsSet[i] = false; // Remove later
  1250. }
  1251. mask >>= 1;
  1252. }
  1253. // We used to check for and correct extreme millis values (near
  1254. // Long.MIN_VALUE or Long.MAX_VALUE) here. Such values would cause
  1255. // overflows from positive to negative (or vice versa) and had to
  1256. // be manually tweaked. We no longer need to do this because we
  1257. // have limited the range of supported dates to those that have a
  1258. // Julian day that fits into an int. This allows us to implement a
  1259. // JULIAN_DAY field and also removes some inelegant code. - Liu
  1260. // 11/6/00
  1261. int32_t millisInDay;
  1262. int32_t days = ClockMath::floorDivide(localMillis, kOneDay, &millisInDay);
  1263. internalSet(UCAL_JULIAN_DAY,days + kEpochStartAsJulianDay);
  1264. #if defined (U_DEBUG_CAL)
  1265. //fprintf(stderr, "%s:%d- Hmm! Jules @ %d, as per %.0lf millis\n",
  1266. //__FILE__, __LINE__, fFields[UCAL_JULIAN_DAY], localMillis);
  1267. #endif
  1268. computeGregorianAndDOWFields(fFields[UCAL_JULIAN_DAY], ec);
  1269. // Call framework method to have subclass compute its fields.
  1270. // These must include, at a minimum, MONTH, DAY_OF_MONTH,
  1271. // EXTENDED_YEAR, YEAR, DAY_OF_YEAR. This method will call internalSet(),
  1272. // which will update stamp[].
  1273. handleComputeFields(fFields[UCAL_JULIAN_DAY], ec);
  1274. // Compute week-related fields, based on the subclass-computed
  1275. // fields computed by handleComputeFields().
  1276. computeWeekFields(ec);
  1277. // Compute time-related fields. These are independent of the date and
  1278. // of the subclass algorithm. They depend only on the local zone
  1279. // wall milliseconds in day.
  1280. if (U_FAILURE(ec)) {
  1281. return;
  1282. }
  1283. fFields[UCAL_MILLISECONDS_IN_DAY] = millisInDay;
  1284. U_ASSERT(getMinimum(UCAL_MILLISECONDS_IN_DAY) <=
  1285. fFields[UCAL_MILLISECONDS_IN_DAY]);
  1286. U_ASSERT(fFields[UCAL_MILLISECONDS_IN_DAY] <=
  1287. getMaximum(UCAL_MILLISECONDS_IN_DAY));
  1288. fFields[UCAL_MILLISECOND] = millisInDay % 1000;
  1289. U_ASSERT(getMinimum(UCAL_MILLISECOND) <= fFields[UCAL_MILLISECOND]);
  1290. U_ASSERT(fFields[UCAL_MILLISECOND] <= getMaximum(UCAL_MILLISECOND));
  1291. millisInDay /= 1000;
  1292. fFields[UCAL_SECOND] = millisInDay % 60;
  1293. U_ASSERT(getMinimum(UCAL_SECOND) <= fFields[UCAL_SECOND]);
  1294. U_ASSERT(fFields[UCAL_SECOND] <= getMaximum(UCAL_SECOND));
  1295. millisInDay /= 60;
  1296. fFields[UCAL_MINUTE] = millisInDay % 60;
  1297. U_ASSERT(getMinimum(UCAL_MINUTE) <= fFields[UCAL_MINUTE]);
  1298. U_ASSERT(fFields[UCAL_MINUTE] <= getMaximum(UCAL_MINUTE));
  1299. millisInDay /= 60;
  1300. fFields[UCAL_HOUR_OF_DAY] = millisInDay;
  1301. U_ASSERT(getMinimum(UCAL_HOUR_OF_DAY) <= fFields[UCAL_HOUR_OF_DAY]);
  1302. U_ASSERT(fFields[UCAL_HOUR_OF_DAY] <= getMaximum(UCAL_HOUR_OF_DAY));
  1303. fFields[UCAL_AM_PM] = millisInDay / 12; // Assume AM == 0
  1304. U_ASSERT(getMinimum(UCAL_AM_PM) <= fFields[UCAL_AM_PM]);
  1305. U_ASSERT(fFields[UCAL_AM_PM] <= getMaximum(UCAL_AM_PM));
  1306. fFields[UCAL_HOUR] = millisInDay % 12;
  1307. U_ASSERT(getMinimum(UCAL_HOUR) <= fFields[UCAL_HOUR]);
  1308. U_ASSERT(fFields[UCAL_HOUR] <= getMaximum(UCAL_HOUR));
  1309. fFields[UCAL_ZONE_OFFSET] = rawOffset;
  1310. U_ASSERT(getMinimum(UCAL_ZONE_OFFSET) <= fFields[UCAL_ZONE_OFFSET]);
  1311. U_ASSERT(fFields[UCAL_ZONE_OFFSET] <= getMaximum(UCAL_ZONE_OFFSET));
  1312. fFields[UCAL_DST_OFFSET] = dstOffset;
  1313. U_ASSERT(getMinimum(UCAL_DST_OFFSET) <= fFields[UCAL_DST_OFFSET]);
  1314. U_ASSERT(fFields[UCAL_DST_OFFSET] <= getMaximum(UCAL_DST_OFFSET));
  1315. }
  1316. uint8_t Calendar::julianDayToDayOfWeek(double julian)
  1317. {
  1318. // If julian is negative, then julian%7 will be negative, so we adjust
  1319. // accordingly. We add 1 because Julian day 0 is Monday.
  1320. int8_t dayOfWeek = (int8_t) uprv_fmod(julian + 1, 7);
  1321. uint8_t result = (uint8_t)(dayOfWeek + ((dayOfWeek < 0) ? (7+UCAL_SUNDAY ) : UCAL_SUNDAY));
  1322. return result;
  1323. }
  1324. /**
  1325. * Compute the Gregorian calendar year, month, and day of month from
  1326. * the given Julian day. These values are not stored in fields, but in
  1327. * member variables gregorianXxx. Also compute the DAY_OF_WEEK and
  1328. * DOW_LOCAL fields.
  1329. */
  1330. void Calendar::computeGregorianAndDOWFields(int32_t julianDay, UErrorCode &ec)
  1331. {
  1332. computeGregorianFields(julianDay, ec);
  1333. if (U_FAILURE(ec)) {
  1334. return;
  1335. }
  1336. // Compute day of week: JD 0 = Monday
  1337. int32_t dow = julianDayToDayOfWeek(julianDay);
  1338. internalSet(UCAL_DAY_OF_WEEK,dow);
  1339. // Calculate 1-based localized day of week
  1340. int32_t dowLocal = dow - getFirstDayOfWeek() + 1;
  1341. if (dowLocal < 1) {
  1342. dowLocal += 7;
  1343. }
  1344. internalSet(UCAL_DOW_LOCAL,dowLocal);
  1345. fFields[UCAL_DOW_LOCAL] = dowLocal;
  1346. }
  1347. /**
  1348. * Compute the Gregorian calendar year, month, and day of month from the
  1349. * Julian day. These values are not stored in fields, but in member
  1350. * variables gregorianXxx. They are used for time zone computations and by
  1351. * subclasses that are Gregorian derivatives. Subclasses may call this
  1352. * method to perform a Gregorian calendar millis->fields computation.
  1353. */
  1354. void Calendar::computeGregorianFields(int32_t julianDay, UErrorCode& ec) {
  1355. if (U_FAILURE(ec)) {
  1356. return;
  1357. }
  1358. int32_t gregorianDayOfWeekUnused;
  1359. Grego::dayToFields(julianDay - kEpochStartAsJulianDay, fGregorianYear, fGregorianMonth, fGregorianDayOfMonth, gregorianDayOfWeekUnused, fGregorianDayOfYear);
  1360. }
  1361. /**
  1362. * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH,
  1363. * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR,
  1364. * DAY_OF_WEEK, and DAY_OF_YEAR. The latter fields are computed by the
  1365. * subclass based on the calendar system.
  1366. *
  1367. * <p>The YEAR_WOY field is computed simplistically. It is equal to YEAR
  1368. * most of the time, but at the year boundary it may be adjusted to YEAR-1
  1369. * or YEAR+1 to reflect the overlap of a week into an adjacent year. In
  1370. * this case, a simple increment or decrement is performed on YEAR, even
  1371. * though this may yield an invalid YEAR value. For instance, if the YEAR
  1372. * is part of a calendar system with an N-year cycle field CYCLE, then
  1373. * incrementing the YEAR may involve incrementing CYCLE and setting YEAR
  1374. * back to 0 or 1. This is not handled by this code, and in fact cannot be
  1375. * simply handled without having subclasses define an entire parallel set of
  1376. * fields for fields larger than or equal to a year. This additional
  1377. * complexity is not warranted, since the intention of the YEAR_WOY field is
  1378. * to support ISO 8601 notation, so it will typically be used with a
  1379. * proleptic Gregorian calendar, which has no field larger than a year.
  1380. */
  1381. void Calendar::computeWeekFields(UErrorCode &ec) {
  1382. if(U_FAILURE(ec)) {
  1383. return;
  1384. }
  1385. int32_t eyear = fFields[UCAL_EXTENDED_YEAR];
  1386. int32_t dayOfWeek = fFields[UCAL_DAY_OF_WEEK];
  1387. int32_t dayOfYear = fFields[UCAL_DAY_OF_YEAR];
  1388. // WEEK_OF_YEAR start
  1389. // Compute the week of the year. For the Gregorian calendar, valid week
  1390. // numbers run from 1 to 52 or 53, depending on the year, the first day
  1391. // of the week, and the minimal days in the first week. For other
  1392. // calendars, the valid range may be different -- it depends on the year
  1393. // length. Days at the start of the year may fall into the last week of
  1394. // the previous year; days at the end of the year may fall into the
  1395. // first week of the next year. ASSUME that the year length is less than
  1396. // 7000 days.
  1397. int32_t yearOfWeekOfYear = eyear;
  1398. int32_t relDow = (dayOfWeek + 7 - getFirstDayOfWeek()) % 7; // 0..6
  1399. int32_t relDowJan1 = (dayOfWeek - dayOfYear + 7001 - getFirstDayOfWeek()) % 7; // 0..6
  1400. int32_t woy = (dayOfYear - 1 + relDowJan1) / 7; // 0..53
  1401. if ((7 - relDowJan1) >= getMinimalDaysInFirstWeek()) {
  1402. ++woy;
  1403. }
  1404. // Adjust for weeks at the year end that overlap into the previous or
  1405. // next calendar year.
  1406. if (woy == 0) {
  1407. // We are the last week of the previous year.
  1408. // Check to see if we are in the last week; if so, we need
  1409. // to handle the case in which we are the first week of the
  1410. // next year.
  1411. int32_t prevDoy = dayOfYear + handleGetYearLength(eyear - 1);
  1412. woy = weekNumber(prevDoy, dayOfWeek);
  1413. yearOfWeekOfYear--;
  1414. } else {
  1415. int32_t lastDoy = handleGetYearLength(eyear);
  1416. // Fast check: For it to be week 1 of the next year, the DOY
  1417. // must be on or after L-5, where L is yearLength(), then it
  1418. // cannot possibly be week 1 of the next year:
  1419. // L-5 L
  1420. // doy: 359 360 361 362 363 364 365 001
  1421. // dow: 1 2 3 4 5 6 7
  1422. if (dayOfYear >= (lastDoy - 5)) {
  1423. int32_t lastRelDow = (relDow + lastDoy - dayOfYear) % 7;
  1424. if (lastRelDow < 0) {
  1425. lastRelDow += 7;
  1426. }
  1427. if (((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) &&
  1428. ((dayOfYear + 7 - relDow) > lastDoy)) {
  1429. woy = 1;
  1430. yearOfWeekOfYear++;
  1431. }
  1432. }
  1433. }
  1434. fFields[UCAL_WEEK_OF_YEAR] = woy;
  1435. fFields[UCAL_YEAR_WOY] = yearOfWeekOfYear;
  1436. // min/max of years are not constrains for caller, so not assert here.
  1437. // WEEK_OF_YEAR end
  1438. int32_t dayOfMonth = fFields[UCAL_DAY_OF_MONTH];
  1439. fFields[UCAL_WEEK_OF_MONTH] = weekNumber(dayOfMonth, dayOfWeek);
  1440. U_ASSERT(getMinimum(UCAL_WEEK_OF_MONTH) <= fFields[UCAL_WEEK_OF_MONTH]);
  1441. U_ASSERT(fFields[UCAL_WEEK_OF_MONTH] <= getMaximum(UCAL_WEEK_OF_MONTH));
  1442. fFields[UCAL_DAY_OF_WEEK_IN_MONTH] = (dayOfMonth-1) / 7 + 1;
  1443. U_ASSERT(getMinimum(UCAL_DAY_OF_WEEK_IN_MONTH) <=
  1444. fFields[UCAL_DAY_OF_WEEK_IN_MONTH]);
  1445. U_ASSERT(fFields[UCAL_DAY_OF_WEEK_IN_MONTH] <=
  1446. getMaximum(UCAL_DAY_OF_WEEK_IN_MONTH));
  1447. #if defined (U_DEBUG_CAL)
  1448. if(fFields[UCAL_DAY_OF_WEEK_IN_MONTH]==0) fprintf(stderr, "%s:%d: DOWIM %d on %g\n",
  1449. __FILE__, __LINE__,fFields[UCAL_DAY_OF_WEEK_IN_MONTH], fTime);
  1450. #endif
  1451. }
  1452. int32_t Calendar::weekNumber(int32_t desiredDay, int32_t dayOfPeriod, int32_t dayOfWeek)
  1453. {
  1454. // Determine the day of the week of the first day of the period
  1455. // in question (either a year or a month). Zero represents the
  1456. // first day of the week on this calendar.
  1457. int32_t periodStartDayOfWeek = (dayOfWeek - getFirstDayOfWeek() - dayOfPeriod + 1) % 7;
  1458. if (periodStartDayOfWeek < 0) periodStartDayOfWeek += 7;
  1459. // Compute the week number. Initially, ignore the first week, which
  1460. // may be fractional (or may not be). We add periodStartDayOfWeek in
  1461. // order to fill out the first week, if it is fractional.
  1462. int32_t weekNo = (desiredDay + periodStartDayOfWeek - 1)/7;
  1463. // If the first week is long enough, then count it. If
  1464. // the minimal days in the first week is one, or if the period start
  1465. // is zero, we always increment weekNo.
  1466. if ((7 - periodStartDayOfWeek) >= getMinimalDaysInFirstWeek()) ++weekNo;
  1467. return weekNo;
  1468. }
  1469. void Calendar::handleComputeFields(int32_t /* julianDay */, UErrorCode& status)
  1470. {
  1471. if (U_FAILURE(status)) {
  1472. return;
  1473. }
  1474. int32_t month = getGregorianMonth();
  1475. internalSet(UCAL_MONTH, month);
  1476. internalSet(UCAL_ORDINAL_MONTH, month);
  1477. internalSet(UCAL_DAY_OF_MONTH, getGregorianDayOfMonth());
  1478. internalSet(UCAL_DAY_OF_YEAR, getGregorianDayOfYear());
  1479. int32_t eyear = getGregorianYear();
  1480. internalSet(UCAL_EXTENDED_YEAR, eyear);
  1481. int32_t era = GregorianCalendar::AD;
  1482. if (eyear < 1) {
  1483. era = GregorianCalendar::BC;
  1484. eyear = 1 - eyear;
  1485. }
  1486. internalSet(UCAL_ERA, era);
  1487. internalSet(UCAL_YEAR, eyear);
  1488. }
  1489. // -------------------------------------
  1490. void Calendar::roll(EDateFields field, int32_t amount, UErrorCode& status)
  1491. {
  1492. roll((UCalendarDateFields)field, amount, status);
  1493. }
  1494. void Calendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) UPRV_NO_SANITIZE_UNDEFINED {
  1495. if (amount == 0) {
  1496. return; // Nothing to do
  1497. }
  1498. complete(status);
  1499. if(U_FAILURE(status)) {
  1500. return;
  1501. }
  1502. switch (field) {
  1503. case UCAL_DAY_OF_MONTH:
  1504. case UCAL_AM_PM:
  1505. case UCAL_MINUTE:
  1506. case UCAL_SECOND:
  1507. case UCAL_MILLISECOND:
  1508. case UCAL_MILLISECONDS_IN_DAY:
  1509. case UCAL_ERA:
  1510. // These are the standard roll instructions. These work for all
  1511. // simple cases, that is, cases in which the limits are fixed, such
  1512. // as the hour, the day of the month, and the era.
  1513. {
  1514. int32_t min = getActualMinimum(field,status);
  1515. int32_t max = getActualMaximum(field,status);
  1516. int32_t gap = max - min + 1;
  1517. int32_t value = internalGet(field) + amount;
  1518. value = (value - min) % gap;
  1519. if (value < 0) {
  1520. value += gap;
  1521. }
  1522. value += min;
  1523. set(field, value);
  1524. return;
  1525. }
  1526. case UCAL_HOUR:
  1527. case UCAL_HOUR_OF_DAY:
  1528. // Rolling the hour is difficult on the ONSET and CEASE days of
  1529. // daylight savings. For example, if the change occurs at
  1530. // 2 AM, we have the following progression:
  1531. // ONSET: 12 Std -> 1 Std -> 3 Dst -> 4 Dst
  1532. // CEASE: 12 Dst -> 1 Dst -> 1 Std -> 2 Std
  1533. // To get around this problem we don't use fields; we manipulate
  1534. // the time in millis directly.
  1535. {
  1536. // Assume min == 0 in calculations below
  1537. double start = getTimeInMillis(status);
  1538. int32_t oldHour = internalGet(field);
  1539. int32_t max = getMaximum(field);
  1540. int32_t newHour = (oldHour + amount) % (max + 1);
  1541. if (newHour < 0) {
  1542. newHour += max + 1;
  1543. }
  1544. setTimeInMillis(start + kOneHour * (newHour - oldHour),status);
  1545. return;
  1546. }
  1547. case UCAL_MONTH:
  1548. case UCAL_ORDINAL_MONTH:
  1549. // Rolling the month involves both pinning the final value
  1550. // and adjusting the DAY_OF_MONTH if necessary. We only adjust the
  1551. // DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
  1552. // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
  1553. {
  1554. int32_t max = getActualMaximum(UCAL_MONTH, status);
  1555. int32_t mon = (internalGet(UCAL_MONTH) + amount) % (max+1);
  1556. if (mon < 0) {
  1557. mon += (max + 1);
  1558. }
  1559. set(UCAL_MONTH, mon);
  1560. // Keep the day of month in range. We don't want to spill over
  1561. // into the next month; e.g., we don't want jan31 + 1 mo -> feb31 ->
  1562. // mar3.
  1563. pinField(UCAL_DAY_OF_MONTH,status);
  1564. return;
  1565. }
  1566. case UCAL_YEAR:
  1567. case UCAL_YEAR_WOY:
  1568. {
  1569. // * If era==0 and years go backwards in time, change sign of amount.
  1570. // * Until we have new API per #9393, we temporarily hardcode knowledge of
  1571. // which calendars have era 0 years that go backwards.
  1572. UBool era0WithYearsThatGoBackwards = false;
  1573. int32_t era = get(UCAL_ERA, status);
  1574. if (era == 0) {
  1575. const char * calType = getType();
  1576. if ( uprv_strcmp(calType,"gregorian")==0 || uprv_strcmp(calType,"roc")==0 || uprv_strcmp(calType,"coptic")==0 ) {
  1577. amount = -amount;
  1578. era0WithYearsThatGoBackwards = true;
  1579. }
  1580. }
  1581. int32_t newYear = internalGet(field) + amount;
  1582. if (era > 0 || newYear >= 1) {
  1583. int32_t maxYear = getActualMaximum(field, status);
  1584. if (maxYear < 32768) {
  1585. // this era has real bounds, roll should wrap years
  1586. if (newYear < 1) {
  1587. newYear = maxYear - ((-newYear) % maxYear);
  1588. } else if (newYear > maxYear) {
  1589. newYear = ((newYear - 1) % maxYear) + 1;
  1590. }
  1591. // else era is unbounded, just pin low year instead of wrapping
  1592. } else if (newYear < 1) {
  1593. newYear = 1;
  1594. }
  1595. // else we are in era 0 with newYear < 1;
  1596. // calendars with years that go backwards must pin the year value at 0,
  1597. // other calendars can have years < 0 in era 0
  1598. } else if (era0WithYearsThatGoBackwards) {
  1599. newYear = 1;
  1600. }
  1601. set(field, newYear);
  1602. pinField(UCAL_MONTH,status);
  1603. pinField(UCAL_ORDINAL_MONTH,status);
  1604. pinField(UCAL_DAY_OF_MONTH,status);
  1605. return;
  1606. }
  1607. case UCAL_EXTENDED_YEAR:
  1608. // Rolling the year can involve pinning the DAY_OF_MONTH.
  1609. set(field, internalGet(field) + amount);
  1610. pinField(UCAL_MONTH,status);
  1611. pinField(UCAL_ORDINAL_MONTH,status);
  1612. pinField(UCAL_DAY_OF_MONTH,status);
  1613. return;
  1614. case UCAL_WEEK_OF_MONTH:
  1615. {
  1616. // This is tricky, because during the roll we may have to shift
  1617. // to a different day of the week. For example:
  1618. // s m t w r f s
  1619. // 1 2 3 4 5
  1620. // 6 7 8 9 10 11 12
  1621. // When rolling from the 6th or 7th back one week, we go to the
  1622. // 1st (assuming that the first partial week counts). The same
  1623. // thing happens at the end of the month.
  1624. // The other tricky thing is that we have to figure out whether
  1625. // the first partial week actually counts or not, based on the
  1626. // minimal first days in the week. And we have to use the
  1627. // correct first day of the week to delineate the week
  1628. // boundaries.
  1629. // Here's our algorithm. First, we find the real boundaries of
  1630. // the month. Then we discard the first partial week if it
  1631. // doesn't count in this locale. Then we fill in the ends with
  1632. // phantom days, so that the first partial week and the last
  1633. // partial week are full weeks. We then have a nice square
  1634. // block of weeks. We do the usual rolling within this block,
  1635. // as is done elsewhere in this method. If we wind up on one of
  1636. // the phantom days that we added, we recognize this and pin to
  1637. // the first or the last day of the month. Easy, eh?
  1638. // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
  1639. // in this locale. We have dow in 0..6.
  1640. int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
  1641. if (dow < 0) dow += 7;
  1642. // Find the day of the week (normalized for locale) for the first
  1643. // of the month.
  1644. int32_t fdm = (dow - internalGet(UCAL_DAY_OF_MONTH) + 1) % 7;
  1645. if (fdm < 0) fdm += 7;
  1646. // Get the first day of the first full week of the month,
  1647. // including phantom days, if any. Figure out if the first week
  1648. // counts or not; if it counts, then fill in phantom days. If
  1649. // not, advance to the first real full week (skip the partial week).
  1650. int32_t start;
  1651. if ((7 - fdm) < getMinimalDaysInFirstWeek())
  1652. start = 8 - fdm; // Skip the first partial week
  1653. else
  1654. start = 1 - fdm; // This may be zero or negative
  1655. // Get the day of the week (normalized for locale) for the last
  1656. // day of the month.
  1657. int32_t monthLen = getActualMaximum(UCAL_DAY_OF_MONTH, status);
  1658. int32_t ldm = (monthLen - internalGet(UCAL_DAY_OF_MONTH) + dow) % 7;
  1659. // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.
  1660. // Get the limit day for the blocked-off rectangular month; that
  1661. // is, the day which is one past the last day of the month,
  1662. // after the month has already been filled in with phantom days
  1663. // to fill out the last week. This day has a normalized DOW of 0.
  1664. int32_t limit = monthLen + 7 - ldm;
  1665. // Now roll between start and (limit - 1).
  1666. int32_t gap = limit - start;
  1667. int32_t day_of_month = (internalGet(UCAL_DAY_OF_MONTH) + amount*7 -
  1668. start) % gap;
  1669. if (day_of_month < 0) day_of_month += gap;
  1670. day_of_month += start;
  1671. // Finally, pin to the real start and end of the month.
  1672. if (day_of_month < 1) day_of_month = 1;
  1673. if (day_of_month > monthLen) day_of_month = monthLen;
  1674. // Set the DAY_OF_MONTH. We rely on the fact that this field
  1675. // takes precedence over everything else (since all other fields
  1676. // are also set at this point). If this fact changes (if the
  1677. // disambiguation algorithm changes) then we will have to unset
  1678. // the appropriate fields here so that DAY_OF_MONTH is attended
  1679. // to.
  1680. set(UCAL_DAY_OF_MONTH, day_of_month);
  1681. return;
  1682. }
  1683. case UCAL_WEEK_OF_YEAR:
  1684. {
  1685. // This follows the outline of WEEK_OF_MONTH, except it applies
  1686. // to the whole year. Please see the comment for WEEK_OF_MONTH
  1687. // for general notes.
  1688. // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
  1689. // in this locale. We have dow in 0..6.
  1690. int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
  1691. if (dow < 0) dow += 7;
  1692. // Find the day of the week (normalized for locale) for the first
  1693. // of the year.
  1694. int32_t fdy = (dow - internalGet(UCAL_DAY_OF_YEAR) + 1) % 7;
  1695. if (fdy < 0) fdy += 7;
  1696. // Get the first day of the first full week of the year,
  1697. // including phantom days, if any. Figure out if the first week
  1698. // counts or not; if it counts, then fill in phantom days. If
  1699. // not, advance to the first real full week (skip the partial week).
  1700. int32_t start;
  1701. if ((7 - fdy) < getMinimalDaysInFirstWeek())
  1702. start = 8 - fdy; // Skip the first partial week
  1703. else
  1704. start = 1 - fdy; // This may be zero or negative
  1705. // Get the day of the week (normalized for locale) for the last
  1706. // day of the year.
  1707. int32_t yearLen = getActualMaximum(UCAL_DAY_OF_YEAR,status);
  1708. int32_t ldy = (yearLen - internalGet(UCAL_DAY_OF_YEAR) + dow) % 7;
  1709. // We know yearLen >= DAY_OF_YEAR so we skip the += 7 step here.
  1710. // Get the limit day for the blocked-off rectangular year; that
  1711. // is, the day which is one past the last day of the year,
  1712. // after the year has already been filled in with phantom days
  1713. // to fill out the last week. This day has a normalized DOW of 0.
  1714. int32_t limit = yearLen + 7 - ldy;
  1715. // Now roll between start and (limit - 1).
  1716. int32_t gap = limit - start;
  1717. int32_t day_of_year = (internalGet(UCAL_DAY_OF_YEAR) + amount*7 -
  1718. start) % gap;
  1719. if (day_of_year < 0) day_of_year += gap;
  1720. day_of_year += start;
  1721. // Finally, pin to the real start and end of the month.
  1722. if (day_of_year < 1) day_of_year = 1;
  1723. if (day_of_year > yearLen) day_of_year = yearLen;
  1724. // Make sure that the year and day of year are attended to by
  1725. // clearing other fields which would normally take precedence.
  1726. // If the disambiguation algorithm is changed, this section will
  1727. // have to be updated as well.
  1728. set(UCAL_DAY_OF_YEAR, day_of_year);
  1729. clear(UCAL_MONTH);
  1730. clear(UCAL_ORDINAL_MONTH);
  1731. return;
  1732. }
  1733. case UCAL_DAY_OF_YEAR:
  1734. {
  1735. // Roll the day of year using millis. Compute the millis for
  1736. // the start of the year, and get the length of the year.
  1737. double delta = amount * kOneDay; // Scale up from days to millis
  1738. double min2 = internalGet(UCAL_DAY_OF_YEAR)-1;
  1739. min2 *= kOneDay;
  1740. min2 = internalGetTime() - min2;
  1741. // double min2 = internalGetTime() - (internalGet(UCAL_DAY_OF_YEAR) - 1.0) * kOneDay;
  1742. double newtime;
  1743. double yearLength = getActualMaximum(UCAL_DAY_OF_YEAR,status);
  1744. double oneYear = yearLength;
  1745. oneYear *= kOneDay;
  1746. newtime = uprv_fmod((internalGetTime() + delta - min2), oneYear);
  1747. if (newtime < 0) newtime += oneYear;
  1748. setTimeInMillis(newtime + min2, status);
  1749. return;
  1750. }
  1751. case UCAL_DAY_OF_WEEK:
  1752. case UCAL_DOW_LOCAL:
  1753. {
  1754. // Roll the day of week using millis. Compute the millis for
  1755. // the start of the week, using the first day of week setting.
  1756. // Restrict the millis to [start, start+7days).
  1757. double delta = amount * kOneDay; // Scale up from days to millis
  1758. // Compute the number of days before the current day in this
  1759. // week. This will be a value 0..6.
  1760. int32_t leadDays = internalGet(field);
  1761. leadDays -= (field == UCAL_DAY_OF_WEEK) ? getFirstDayOfWeek() : 1;
  1762. if (leadDays < 0) leadDays += 7;
  1763. double min2 = internalGetTime() - leadDays * kOneDay;
  1764. double newtime = uprv_fmod((internalGetTime() + delta - min2), kOneWeek);
  1765. if (newtime < 0) newtime += kOneWeek;
  1766. setTimeInMillis(newtime + min2, status);
  1767. return;
  1768. }
  1769. case UCAL_DAY_OF_WEEK_IN_MONTH:
  1770. {
  1771. // Roll the day of week in the month using millis. Determine
  1772. // the first day of the week in the month, and then the last,
  1773. // and then roll within that range.
  1774. double delta = amount * kOneWeek; // Scale up from weeks to millis
  1775. // Find the number of same days of the week before this one
  1776. // in this month.
  1777. int32_t preWeeks = (internalGet(UCAL_DAY_OF_MONTH) - 1) / 7;
  1778. // Find the number of same days of the week after this one
  1779. // in this month.
  1780. int32_t postWeeks = (getActualMaximum(UCAL_DAY_OF_MONTH,status) -
  1781. internalGet(UCAL_DAY_OF_MONTH)) / 7;
  1782. // From these compute the min and gap millis for rolling.
  1783. double min2 = internalGetTime() - preWeeks * kOneWeek;
  1784. double gap2 = kOneWeek * (preWeeks + postWeeks + 1); // Must add 1!
  1785. // Roll within this range
  1786. double newtime = uprv_fmod((internalGetTime() + delta - min2), gap2);
  1787. if (newtime < 0) newtime += gap2;
  1788. setTimeInMillis(newtime + min2, status);
  1789. return;
  1790. }
  1791. case UCAL_JULIAN_DAY:
  1792. set(field, internalGet(field) + amount);
  1793. return;
  1794. default:
  1795. // Other fields cannot be rolled by this method
  1796. #if defined (U_DEBUG_CAL)
  1797. fprintf(stderr, "%s:%d: ILLEGAL ARG because of roll on non-rollable field %s\n",
  1798. __FILE__, __LINE__,fldName(field));
  1799. #endif
  1800. status = U_ILLEGAL_ARGUMENT_ERROR;
  1801. }
  1802. }
  1803. void Calendar::add(EDateFields field, int32_t amount, UErrorCode& status)
  1804. {
  1805. Calendar::add((UCalendarDateFields)field, amount, status);
  1806. }
  1807. // -------------------------------------
  1808. void Calendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status)
  1809. {
  1810. if (U_FAILURE(status)) {
  1811. return;
  1812. }
  1813. if (amount == 0) {
  1814. return; // Do nothing!
  1815. }
  1816. // We handle most fields in the same way. The algorithm is to add
  1817. // a computed amount of millis to the current millis. The only
  1818. // wrinkle is with DST (and/or a change to the zone's UTC offset, which
  1819. // we'll include with DST) -- for some fields, like the DAY_OF_MONTH,
  1820. // we don't want the wall time to shift due to changes in DST. If the
  1821. // result of the add operation is to move from DST to Standard, or
  1822. // vice versa, we need to adjust by an hour forward or back,
  1823. // respectively. For such fields we set keepWallTimeInvariant to true.
  1824. // We only adjust the DST for fields larger than an hour. For
  1825. // fields smaller than an hour, we cannot adjust for DST without
  1826. // causing problems. for instance, if you add one hour to April 5,
  1827. // 1998, 1:00 AM, in PST, the time becomes "2:00 AM PDT" (an
  1828. // illegal value), but then the adjustment sees the change and
  1829. // compensates by subtracting an hour. As a result the time
  1830. // doesn't advance at all.
  1831. // For some fields larger than a day, such as a UCAL_MONTH, we pin the
  1832. // UCAL_DAY_OF_MONTH. This allows <March 31>.add(UCAL_MONTH, 1) to be
  1833. // <April 30>, rather than <April 31> => <May 1>.
  1834. double delta = amount; // delta in ms
  1835. UBool keepWallTimeInvariant = true;
  1836. switch (field) {
  1837. case UCAL_ERA:
  1838. set(field, get(field, status) + amount);
  1839. pinField(UCAL_ERA, status);
  1840. return;
  1841. case UCAL_YEAR:
  1842. case UCAL_YEAR_WOY:
  1843. {
  1844. // * If era=0 and years go backwards in time, change sign of amount.
  1845. // * Until we have new API per #9393, we temporarily hardcode knowledge of
  1846. // which calendars have era 0 years that go backwards.
  1847. // * Note that for UCAL_YEAR (but not UCAL_YEAR_WOY) we could instead handle
  1848. // this by applying the amount to the UCAL_EXTENDED_YEAR field; but since
  1849. // we would still need to handle UCAL_YEAR_WOY as below, might as well
  1850. // also handle UCAL_YEAR the same way.
  1851. int32_t era = get(UCAL_ERA, status);
  1852. if (era == 0) {
  1853. const char * calType = getType();
  1854. if ( uprv_strcmp(calType,"gregorian")==0 || uprv_strcmp(calType,"roc")==0 || uprv_strcmp(calType,"coptic")==0 ) {
  1855. amount = -amount;
  1856. }
  1857. }
  1858. }
  1859. // Fall through into normal handling
  1860. U_FALLTHROUGH;
  1861. case UCAL_EXTENDED_YEAR:
  1862. case UCAL_MONTH:
  1863. case UCAL_ORDINAL_MONTH:
  1864. {
  1865. UBool oldLenient = isLenient();
  1866. setLenient(true);
  1867. set(field, get(field, status) + amount);
  1868. pinField(UCAL_DAY_OF_MONTH, status);
  1869. if(oldLenient==false) {
  1870. complete(status); /* force recalculate */
  1871. setLenient(oldLenient);
  1872. }
  1873. }
  1874. return;
  1875. case UCAL_WEEK_OF_YEAR:
  1876. case UCAL_WEEK_OF_MONTH:
  1877. case UCAL_DAY_OF_WEEK_IN_MONTH:
  1878. delta *= kOneWeek;
  1879. break;
  1880. case UCAL_AM_PM:
  1881. delta *= 12 * kOneHour;
  1882. break;
  1883. case UCAL_DAY_OF_MONTH:
  1884. case UCAL_DAY_OF_YEAR:
  1885. case UCAL_DAY_OF_WEEK:
  1886. case UCAL_DOW_LOCAL:
  1887. case UCAL_JULIAN_DAY:
  1888. delta *= kOneDay;
  1889. break;
  1890. case UCAL_HOUR_OF_DAY:
  1891. case UCAL_HOUR:
  1892. delta *= kOneHour;
  1893. keepWallTimeInvariant = false;
  1894. break;
  1895. case UCAL_MINUTE:
  1896. delta *= kOneMinute;
  1897. keepWallTimeInvariant = false;
  1898. break;
  1899. case UCAL_SECOND:
  1900. delta *= kOneSecond;
  1901. keepWallTimeInvariant = false;
  1902. break;
  1903. case UCAL_MILLISECOND:
  1904. case UCAL_MILLISECONDS_IN_DAY:
  1905. keepWallTimeInvariant = false;
  1906. break;
  1907. default:
  1908. #if defined (U_DEBUG_CAL)
  1909. fprintf(stderr, "%s:%d: ILLEGAL ARG because field %s not addable",
  1910. __FILE__, __LINE__, fldName(field));
  1911. #endif
  1912. status = U_ILLEGAL_ARGUMENT_ERROR;
  1913. return;
  1914. // throw new IllegalArgumentException("Calendar.add(" + fieldName(field) +
  1915. // ") not supported");
  1916. }
  1917. // In order to keep the wall time invariant (for fields where this is
  1918. // appropriate), check the combined DST & ZONE offset before and
  1919. // after the add() operation. If it changes, then adjust the millis
  1920. // to compensate.
  1921. int32_t prevOffset = 0;
  1922. int32_t prevWallTime = 0;
  1923. if (keepWallTimeInvariant) {
  1924. prevOffset = get(UCAL_DST_OFFSET, status) + get(UCAL_ZONE_OFFSET, status);
  1925. prevWallTime = get(UCAL_MILLISECONDS_IN_DAY, status);
  1926. }
  1927. setTimeInMillis(getTimeInMillis(status) + delta, status);
  1928. if (keepWallTimeInvariant) {
  1929. int32_t newWallTime = get(UCAL_MILLISECONDS_IN_DAY, status);
  1930. if (newWallTime != prevWallTime) {
  1931. // There is at least one zone transition between the base
  1932. // time and the result time. As the result, wall time has
  1933. // changed.
  1934. UDate t = internalGetTime();
  1935. int32_t newOffset = get(UCAL_DST_OFFSET, status) + get(UCAL_ZONE_OFFSET, status);
  1936. if (newOffset != prevOffset) {
  1937. // When the difference of the previous UTC offset and
  1938. // the new UTC offset exceeds 1 full day, we do not want
  1939. // to roll over/back the date. For now, this only happens
  1940. // in Samoa (Pacific/Apia) on Dec 30, 2011. See ticket:9452.
  1941. int32_t adjAmount = prevOffset - newOffset;
  1942. adjAmount = adjAmount >= 0 ? adjAmount % (int32_t)kOneDay : -(-adjAmount % (int32_t)kOneDay);
  1943. if (adjAmount != 0) {
  1944. setTimeInMillis(t + adjAmount, status);
  1945. newWallTime = get(UCAL_MILLISECONDS_IN_DAY, status);
  1946. }
  1947. if (newWallTime != prevWallTime) {
  1948. // The result wall time or adjusted wall time was shifted because
  1949. // the target wall time does not exist on the result date.
  1950. switch (fSkippedWallTime) {
  1951. case UCAL_WALLTIME_FIRST:
  1952. if (adjAmount > 0) {
  1953. setTimeInMillis(t, status);
  1954. }
  1955. break;
  1956. case UCAL_WALLTIME_LAST:
  1957. if (adjAmount < 0) {
  1958. setTimeInMillis(t, status);
  1959. }
  1960. break;
  1961. case UCAL_WALLTIME_NEXT_VALID:
  1962. UDate tmpT = adjAmount > 0 ? internalGetTime() : t;
  1963. UDate immediatePrevTrans;
  1964. UBool hasTransition = getImmediatePreviousZoneTransition(tmpT, &immediatePrevTrans, status);
  1965. if (U_SUCCESS(status) && hasTransition) {
  1966. setTimeInMillis(immediatePrevTrans, status);
  1967. }
  1968. break;
  1969. }
  1970. }
  1971. }
  1972. }
  1973. }
  1974. }
  1975. // -------------------------------------
  1976. int32_t Calendar::fieldDifference(UDate when, EDateFields field, UErrorCode& status) {
  1977. return fieldDifference(when, (UCalendarDateFields) field, status);
  1978. }
  1979. int32_t Calendar::fieldDifference(UDate targetMs, UCalendarDateFields field, UErrorCode& ec) {
  1980. if (U_FAILURE(ec)) return 0;
  1981. int32_t min = 0;
  1982. double startMs = getTimeInMillis(ec);
  1983. // Always add from the start millis. This accommodates
  1984. // operations like adding years from February 29, 2000 up to
  1985. // February 29, 2004. If 1, 1, 1, 1 is added to the year
  1986. // field, the DOM gets pinned to 28 and stays there, giving an
  1987. // incorrect DOM difference of 1. We have to add 1, reset, 2,
  1988. // reset, 3, reset, 4.
  1989. if (startMs < targetMs) {
  1990. int32_t max = 1;
  1991. // Find a value that is too large
  1992. while (U_SUCCESS(ec)) {
  1993. setTimeInMillis(startMs, ec);
  1994. add(field, max, ec);
  1995. double ms = getTimeInMillis(ec);
  1996. if (ms == targetMs) {
  1997. return max;
  1998. } else if (ms > targetMs) {
  1999. break;
  2000. } else if (max < INT32_MAX) {
  2001. min = max;
  2002. max <<= 1;
  2003. if (max < 0) {
  2004. max = INT32_MAX;
  2005. }
  2006. } else {
  2007. // Field difference too large to fit into int32_t
  2008. #if defined (U_DEBUG_CAL)
  2009. fprintf(stderr, "%s:%d: ILLEGAL ARG because field %s's max too large for int32_t\n",
  2010. __FILE__, __LINE__, fldName(field));
  2011. #endif
  2012. ec = U_ILLEGAL_ARGUMENT_ERROR;
  2013. }
  2014. }
  2015. // Do a binary search
  2016. while ((max - min) > 1 && U_SUCCESS(ec)) {
  2017. int32_t t = min + (max - min)/2; // make sure intermediate values don't exceed INT32_MAX
  2018. setTimeInMillis(startMs, ec);
  2019. add(field, t, ec);
  2020. double ms = getTimeInMillis(ec);
  2021. if (ms == targetMs) {
  2022. return t;
  2023. } else if (ms > targetMs) {
  2024. max = t;
  2025. } else {
  2026. min = t;
  2027. }
  2028. }
  2029. } else if (startMs > targetMs) {
  2030. int32_t max = -1;
  2031. // Find a value that is too small
  2032. while (U_SUCCESS(ec)) {
  2033. setTimeInMillis(startMs, ec);
  2034. add(field, max, ec);
  2035. double ms = getTimeInMillis(ec);
  2036. if (ms == targetMs) {
  2037. return max;
  2038. } else if (ms < targetMs) {
  2039. break;
  2040. } else {
  2041. min = max;
  2042. max = (int32_t)((uint32_t)(max) << 1);
  2043. if (max == 0) {
  2044. // Field difference too large to fit into int32_t
  2045. #if defined (U_DEBUG_CAL)
  2046. fprintf(stderr, "%s:%d: ILLEGAL ARG because field %s's max too large for int32_t\n",
  2047. __FILE__, __LINE__, fldName(field));
  2048. #endif
  2049. ec = U_ILLEGAL_ARGUMENT_ERROR;
  2050. }
  2051. }
  2052. }
  2053. // Do a binary search
  2054. while ((min - max) > 1 && U_SUCCESS(ec)) {
  2055. int32_t t = min + (max - min)/2; // make sure intermediate values don't exceed INT32_MAX
  2056. setTimeInMillis(startMs, ec);
  2057. add(field, t, ec);
  2058. double ms = getTimeInMillis(ec);
  2059. if (ms == targetMs) {
  2060. return t;
  2061. } else if (ms < targetMs) {
  2062. max = t;
  2063. } else {
  2064. min = t;
  2065. }
  2066. }
  2067. }
  2068. // Set calendar to end point
  2069. setTimeInMillis(startMs, ec);
  2070. add(field, min, ec);
  2071. /* Test for buffer overflows */
  2072. if(U_FAILURE(ec)) {
  2073. return 0;
  2074. }
  2075. return min;
  2076. }
  2077. // -------------------------------------
  2078. void
  2079. Calendar::adoptTimeZone(TimeZone* zone)
  2080. {
  2081. // Do nothing if passed-in zone is nullptr
  2082. if (zone == nullptr) return;
  2083. // fZone should always be non-null
  2084. delete fZone;
  2085. fZone = zone;
  2086. // if the zone changes, we need to recompute the time fields
  2087. fAreFieldsSet = false;
  2088. }
  2089. // -------------------------------------
  2090. void
  2091. Calendar::setTimeZone(const TimeZone& zone)
  2092. {
  2093. adoptTimeZone(zone.clone());
  2094. }
  2095. // -------------------------------------
  2096. const TimeZone&
  2097. Calendar::getTimeZone() const
  2098. {
  2099. U_ASSERT(fZone != nullptr);
  2100. return *fZone;
  2101. }
  2102. // -------------------------------------
  2103. TimeZone*
  2104. Calendar::orphanTimeZone()
  2105. {
  2106. // we let go of the time zone; the new time zone is the system default time zone
  2107. TimeZone *defaultZone = TimeZone::createDefault();
  2108. if (defaultZone == nullptr) {
  2109. // No error handling available. Must keep fZone non-nullptr, there are many unchecked uses.
  2110. return nullptr;
  2111. }
  2112. TimeZone *z = fZone;
  2113. fZone = defaultZone;
  2114. return z;
  2115. }
  2116. // -------------------------------------
  2117. void
  2118. Calendar::setLenient(UBool lenient)
  2119. {
  2120. fLenient = lenient;
  2121. }
  2122. // -------------------------------------
  2123. UBool
  2124. Calendar::isLenient() const
  2125. {
  2126. return fLenient;
  2127. }
  2128. // -------------------------------------
  2129. void
  2130. Calendar::setRepeatedWallTimeOption(UCalendarWallTimeOption option)
  2131. {
  2132. if (option == UCAL_WALLTIME_LAST || option == UCAL_WALLTIME_FIRST) {
  2133. fRepeatedWallTime = option;
  2134. }
  2135. }
  2136. // -------------------------------------
  2137. UCalendarWallTimeOption
  2138. Calendar::getRepeatedWallTimeOption() const
  2139. {
  2140. return fRepeatedWallTime;
  2141. }
  2142. // -------------------------------------
  2143. void
  2144. Calendar::setSkippedWallTimeOption(UCalendarWallTimeOption option)
  2145. {
  2146. fSkippedWallTime = option;
  2147. }
  2148. // -------------------------------------
  2149. UCalendarWallTimeOption
  2150. Calendar::getSkippedWallTimeOption() const
  2151. {
  2152. return fSkippedWallTime;
  2153. }
  2154. // -------------------------------------
  2155. void
  2156. Calendar::setFirstDayOfWeek(UCalendarDaysOfWeek value) UPRV_NO_SANITIZE_UNDEFINED {
  2157. if (fFirstDayOfWeek != value &&
  2158. value >= UCAL_SUNDAY && value <= UCAL_SATURDAY) {
  2159. fFirstDayOfWeek = value;
  2160. fAreFieldsSet = false;
  2161. }
  2162. }
  2163. // -------------------------------------
  2164. Calendar::EDaysOfWeek
  2165. Calendar::getFirstDayOfWeek() const
  2166. {
  2167. return (Calendar::EDaysOfWeek)fFirstDayOfWeek;
  2168. }
  2169. UCalendarDaysOfWeek
  2170. Calendar::getFirstDayOfWeek(UErrorCode & /*status*/) const
  2171. {
  2172. return fFirstDayOfWeek;
  2173. }
  2174. // -------------------------------------
  2175. void
  2176. Calendar::setMinimalDaysInFirstWeek(uint8_t value)
  2177. {
  2178. // Values less than 1 have the same effect as 1; values greater
  2179. // than 7 have the same effect as 7. However, we normalize values
  2180. // so operator== and so forth work.
  2181. if (value < 1) {
  2182. value = 1;
  2183. } else if (value > 7) {
  2184. value = 7;
  2185. }
  2186. if (fMinimalDaysInFirstWeek != value) {
  2187. fMinimalDaysInFirstWeek = value;
  2188. fAreFieldsSet = false;
  2189. }
  2190. }
  2191. // -------------------------------------
  2192. uint8_t
  2193. Calendar::getMinimalDaysInFirstWeek() const
  2194. {
  2195. return fMinimalDaysInFirstWeek;
  2196. }
  2197. // -------------------------------------
  2198. // weekend functions, just dummy implementations for now (for API freeze)
  2199. UCalendarWeekdayType
  2200. Calendar::getDayOfWeekType(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const
  2201. {
  2202. if (U_FAILURE(status)) {
  2203. return UCAL_WEEKDAY;
  2204. }
  2205. if (dayOfWeek < UCAL_SUNDAY || dayOfWeek > UCAL_SATURDAY) {
  2206. status = U_ILLEGAL_ARGUMENT_ERROR;
  2207. return UCAL_WEEKDAY;
  2208. }
  2209. if (fWeekendOnset == fWeekendCease) {
  2210. if (dayOfWeek != fWeekendOnset)
  2211. return UCAL_WEEKDAY;
  2212. return (fWeekendOnsetMillis == 0) ? UCAL_WEEKEND : UCAL_WEEKEND_ONSET;
  2213. }
  2214. if (fWeekendOnset < fWeekendCease) {
  2215. if (dayOfWeek < fWeekendOnset || dayOfWeek > fWeekendCease) {
  2216. return UCAL_WEEKDAY;
  2217. }
  2218. } else {
  2219. if (dayOfWeek > fWeekendCease && dayOfWeek < fWeekendOnset) {
  2220. return UCAL_WEEKDAY;
  2221. }
  2222. }
  2223. if (dayOfWeek == fWeekendOnset) {
  2224. return (fWeekendOnsetMillis == 0) ? UCAL_WEEKEND : UCAL_WEEKEND_ONSET;
  2225. }
  2226. if (dayOfWeek == fWeekendCease) {
  2227. return (fWeekendCeaseMillis >= 86400000) ? UCAL_WEEKEND : UCAL_WEEKEND_CEASE;
  2228. }
  2229. return UCAL_WEEKEND;
  2230. }
  2231. int32_t
  2232. Calendar::getWeekendTransition(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const
  2233. {
  2234. if (U_FAILURE(status)) {
  2235. return 0;
  2236. }
  2237. if (dayOfWeek == fWeekendOnset) {
  2238. return fWeekendOnsetMillis;
  2239. } else if (dayOfWeek == fWeekendCease) {
  2240. return fWeekendCeaseMillis;
  2241. }
  2242. status = U_ILLEGAL_ARGUMENT_ERROR;
  2243. return 0;
  2244. }
  2245. UBool
  2246. Calendar::isWeekend(UDate date, UErrorCode &status) const
  2247. {
  2248. if (U_FAILURE(status)) {
  2249. return false;
  2250. }
  2251. // clone the calendar so we don't mess with the real one.
  2252. Calendar *work = this->clone();
  2253. if (work == nullptr) {
  2254. status = U_MEMORY_ALLOCATION_ERROR;
  2255. return false;
  2256. }
  2257. UBool result = false;
  2258. work->setTime(date, status);
  2259. if (U_SUCCESS(status)) {
  2260. result = work->isWeekend();
  2261. }
  2262. delete work;
  2263. return result;
  2264. }
  2265. UBool
  2266. Calendar::isWeekend() const
  2267. {
  2268. UErrorCode status = U_ZERO_ERROR;
  2269. UCalendarDaysOfWeek dayOfWeek = (UCalendarDaysOfWeek)get(UCAL_DAY_OF_WEEK, status);
  2270. UCalendarWeekdayType dayType = getDayOfWeekType(dayOfWeek, status);
  2271. if (U_SUCCESS(status)) {
  2272. switch (dayType) {
  2273. case UCAL_WEEKDAY:
  2274. return false;
  2275. case UCAL_WEEKEND:
  2276. return true;
  2277. case UCAL_WEEKEND_ONSET:
  2278. case UCAL_WEEKEND_CEASE:
  2279. // Use internalGet() because the above call to get() populated all fields.
  2280. {
  2281. int32_t millisInDay = internalGet(UCAL_MILLISECONDS_IN_DAY);
  2282. int32_t transitionMillis = getWeekendTransition(dayOfWeek, status);
  2283. if (U_SUCCESS(status)) {
  2284. return (dayType == UCAL_WEEKEND_ONSET)?
  2285. (millisInDay >= transitionMillis):
  2286. (millisInDay < transitionMillis);
  2287. }
  2288. // else fall through, return false
  2289. U_FALLTHROUGH;
  2290. }
  2291. default:
  2292. break;
  2293. }
  2294. }
  2295. return false;
  2296. }
  2297. // ------------------------------------- limits
  2298. int32_t
  2299. Calendar::getMinimum(EDateFields field) const {
  2300. return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MINIMUM);
  2301. }
  2302. int32_t
  2303. Calendar::getMinimum(UCalendarDateFields field) const
  2304. {
  2305. return getLimit(field,UCAL_LIMIT_MINIMUM);
  2306. }
  2307. // -------------------------------------
  2308. int32_t
  2309. Calendar::getMaximum(EDateFields field) const
  2310. {
  2311. return getLimit((UCalendarDateFields) field,UCAL_LIMIT_MAXIMUM);
  2312. }
  2313. int32_t
  2314. Calendar::getMaximum(UCalendarDateFields field) const
  2315. {
  2316. return getLimit(field,UCAL_LIMIT_MAXIMUM);
  2317. }
  2318. // -------------------------------------
  2319. int32_t
  2320. Calendar::getGreatestMinimum(EDateFields field) const
  2321. {
  2322. return getLimit((UCalendarDateFields)field,UCAL_LIMIT_GREATEST_MINIMUM);
  2323. }
  2324. int32_t
  2325. Calendar::getGreatestMinimum(UCalendarDateFields field) const
  2326. {
  2327. return getLimit(field,UCAL_LIMIT_GREATEST_MINIMUM);
  2328. }
  2329. // -------------------------------------
  2330. int32_t
  2331. Calendar::getLeastMaximum(EDateFields field) const
  2332. {
  2333. return getLimit((UCalendarDateFields) field,UCAL_LIMIT_LEAST_MAXIMUM);
  2334. }
  2335. int32_t
  2336. Calendar::getLeastMaximum(UCalendarDateFields field) const
  2337. {
  2338. return getLimit( field,UCAL_LIMIT_LEAST_MAXIMUM);
  2339. }
  2340. // -------------------------------------
  2341. int32_t
  2342. Calendar::getActualMinimum(EDateFields field, UErrorCode& status) const
  2343. {
  2344. return getActualMinimum((UCalendarDateFields) field, status);
  2345. }
  2346. int32_t Calendar::getLimit(UCalendarDateFields field, ELimitType limitType) const {
  2347. switch (field) {
  2348. case UCAL_DAY_OF_WEEK:
  2349. case UCAL_AM_PM:
  2350. case UCAL_HOUR:
  2351. case UCAL_HOUR_OF_DAY:
  2352. case UCAL_MINUTE:
  2353. case UCAL_SECOND:
  2354. case UCAL_MILLISECOND:
  2355. case UCAL_ZONE_OFFSET:
  2356. case UCAL_DST_OFFSET:
  2357. case UCAL_DOW_LOCAL:
  2358. case UCAL_JULIAN_DAY:
  2359. case UCAL_MILLISECONDS_IN_DAY:
  2360. case UCAL_IS_LEAP_MONTH:
  2361. return kCalendarLimits[field][limitType];
  2362. case UCAL_WEEK_OF_MONTH:
  2363. {
  2364. int32_t limit;
  2365. if (limitType == UCAL_LIMIT_MINIMUM) {
  2366. limit = getMinimalDaysInFirstWeek() == 1 ? 1 : 0;
  2367. } else if (limitType == UCAL_LIMIT_GREATEST_MINIMUM) {
  2368. limit = 1;
  2369. } else {
  2370. int32_t minDaysInFirst = getMinimalDaysInFirstWeek();
  2371. int32_t daysInMonth = handleGetLimit(UCAL_DAY_OF_MONTH, limitType);
  2372. if (limitType == UCAL_LIMIT_LEAST_MAXIMUM) {
  2373. limit = (daysInMonth + (7 - minDaysInFirst)) / 7;
  2374. } else { // limitType == UCAL_LIMIT_MAXIMUM
  2375. limit = (daysInMonth + 6 + (7 - minDaysInFirst)) / 7;
  2376. }
  2377. }
  2378. return limit;
  2379. }
  2380. default:
  2381. return handleGetLimit(field, limitType);
  2382. }
  2383. }
  2384. int32_t
  2385. Calendar::getActualMinimum(UCalendarDateFields field, UErrorCode& status) const
  2386. {
  2387. if (U_FAILURE(status)) {
  2388. return 0;
  2389. }
  2390. int32_t fieldValue = getGreatestMinimum(field);
  2391. int32_t endValue = getMinimum(field);
  2392. // if we know that the minimum value is always the same, just return it
  2393. if (fieldValue == endValue) {
  2394. return fieldValue;
  2395. }
  2396. // clone the calendar so we don't mess with the real one, and set it to
  2397. // accept anything for the field values
  2398. Calendar *work = this->clone();
  2399. if (work == nullptr) {
  2400. status = U_MEMORY_ALLOCATION_ERROR;
  2401. return 0;
  2402. }
  2403. work->setLenient(true);
  2404. // now try each value from getLeastMaximum() to getMaximum() one by one until
  2405. // we get a value that normalizes to another value. The last value that
  2406. // normalizes to itself is the actual minimum for the current date
  2407. int32_t result = fieldValue;
  2408. do {
  2409. work->set(field, fieldValue);
  2410. if (work->get(field, status) != fieldValue) {
  2411. break;
  2412. }
  2413. else {
  2414. result = fieldValue;
  2415. fieldValue--;
  2416. }
  2417. } while (fieldValue >= endValue);
  2418. delete work;
  2419. /* Test for buffer overflows */
  2420. if(U_FAILURE(status)) {
  2421. return 0;
  2422. }
  2423. return result;
  2424. }
  2425. // -------------------------------------
  2426. UBool
  2427. Calendar::inDaylightTime(UErrorCode& status) const
  2428. {
  2429. if (U_FAILURE(status) || !getTimeZone().useDaylightTime()) {
  2430. return false;
  2431. }
  2432. // Force an update of the state of the Calendar.
  2433. ((Calendar*)this)->complete(status); // cast away const
  2434. return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : false);
  2435. }
  2436. bool
  2437. Calendar::inTemporalLeapYear(UErrorCode& status) const
  2438. {
  2439. // Default to Gregorian based leap year rule.
  2440. return getActualMaximum(UCAL_DAY_OF_YEAR, status) == 366;
  2441. }
  2442. // -------------------------------------
  2443. static const char * const gTemporalMonthCodes[] = {
  2444. "M01", "M02", "M03", "M04", "M05", "M06",
  2445. "M07", "M08", "M09", "M10", "M11", "M12", nullptr
  2446. };
  2447. const char*
  2448. Calendar::getTemporalMonthCode(UErrorCode& status) const
  2449. {
  2450. int32_t month = get(UCAL_MONTH, status);
  2451. if (U_FAILURE(status)) return nullptr;
  2452. U_ASSERT(month < 12);
  2453. U_ASSERT(internalGet(UCAL_IS_LEAP_MONTH) == 0);
  2454. return gTemporalMonthCodes[month];
  2455. }
  2456. void
  2457. Calendar::setTemporalMonthCode(const char* code, UErrorCode& status )
  2458. {
  2459. if (U_FAILURE(status)) return;
  2460. int32_t len = static_cast<int32_t>(uprv_strlen(code));
  2461. if (len == 3 && code[0] == 'M') {
  2462. for (int m = 0; gTemporalMonthCodes[m] != nullptr; m++) {
  2463. if (uprv_strcmp(code, gTemporalMonthCodes[m]) == 0) {
  2464. set(UCAL_MONTH, m);
  2465. set(UCAL_IS_LEAP_MONTH, 0);
  2466. return;
  2467. }
  2468. }
  2469. }
  2470. status = U_ILLEGAL_ARGUMENT_ERROR;
  2471. }
  2472. // -------------------------------------
  2473. /**
  2474. * Ensure that each field is within its valid range by calling {@link
  2475. * #validateField(int)} on each field that has been set. This method
  2476. * should only be called if this calendar is not lenient.
  2477. * @see #isLenient
  2478. * @see #validateField(int)
  2479. */
  2480. void Calendar::validateFields(UErrorCode &status) {
  2481. if (U_FAILURE(status)) {
  2482. return;
  2483. }
  2484. for (int32_t field = 0; U_SUCCESS(status) && (field < UCAL_FIELD_COUNT); field++) {
  2485. if (fStamp[field] >= kMinimumUserStamp) {
  2486. validateField((UCalendarDateFields)field, status);
  2487. }
  2488. }
  2489. }
  2490. /**
  2491. * Validate a single field of this calendar. Subclasses should
  2492. * override this method to validate any calendar-specific fields.
  2493. * Generic fields can be handled by
  2494. * <code>Calendar.validateField()</code>.
  2495. * @see #validateField(int, int, int)
  2496. */
  2497. void Calendar::validateField(UCalendarDateFields field, UErrorCode &status) {
  2498. if (U_FAILURE(status)) {
  2499. return;
  2500. }
  2501. int32_t y;
  2502. switch (field) {
  2503. case UCAL_DAY_OF_MONTH:
  2504. y = handleGetExtendedYear();
  2505. validateField(field, 1, handleGetMonthLength(y, internalGetMonth()), status);
  2506. break;
  2507. case UCAL_DAY_OF_YEAR:
  2508. y = handleGetExtendedYear();
  2509. validateField(field, 1, handleGetYearLength(y), status);
  2510. break;
  2511. case UCAL_DAY_OF_WEEK_IN_MONTH:
  2512. if (internalGet(field) == 0) {
  2513. #if defined (U_DEBUG_CAL)
  2514. fprintf(stderr, "%s:%d: ILLEGAL ARG because DOW in month cannot be 0\n",
  2515. __FILE__, __LINE__);
  2516. #endif
  2517. status = U_ILLEGAL_ARGUMENT_ERROR; // "DAY_OF_WEEK_IN_MONTH cannot be zero"
  2518. return;
  2519. }
  2520. validateField(field, getMinimum(field), getMaximum(field), status);
  2521. break;
  2522. default:
  2523. validateField(field, getMinimum(field), getMaximum(field), status);
  2524. break;
  2525. }
  2526. }
  2527. /**
  2528. * Validate a single field of this calendar given its minimum and
  2529. * maximum allowed value. If the field is out of range, throw a
  2530. * descriptive <code>IllegalArgumentException</code>. Subclasses may
  2531. * use this method in their implementation of {@link
  2532. * #validateField(int)}.
  2533. */
  2534. void Calendar::validateField(UCalendarDateFields field, int32_t min, int32_t max, UErrorCode& status)
  2535. {
  2536. if (U_FAILURE(status)) {
  2537. return;
  2538. }
  2539. int32_t value = fFields[field];
  2540. if (value < min || value > max) {
  2541. #if defined (U_DEBUG_CAL)
  2542. fprintf(stderr, "%s:%d: ILLEGAL ARG because of field %s out of range %d..%d at %d\n",
  2543. __FILE__, __LINE__,fldName(field),min,max,value);
  2544. #endif
  2545. status = U_ILLEGAL_ARGUMENT_ERROR;
  2546. return;
  2547. }
  2548. }
  2549. // -------------------------
  2550. const UFieldResolutionTable* Calendar::getFieldResolutionTable() const {
  2551. return kDatePrecedence;
  2552. }
  2553. UCalendarDateFields Calendar::newerField(UCalendarDateFields defaultField, UCalendarDateFields alternateField) const
  2554. {
  2555. if (fStamp[alternateField] > fStamp[defaultField]) {
  2556. return alternateField;
  2557. }
  2558. return defaultField;
  2559. }
  2560. UCalendarDateFields Calendar::resolveFields(const UFieldResolutionTable* precedenceTable) const {
  2561. int32_t bestField = UCAL_FIELD_COUNT;
  2562. int32_t tempBestField;
  2563. for (int32_t g=0; precedenceTable[g][0][0] != -1 && (bestField == UCAL_FIELD_COUNT); ++g) {
  2564. int32_t bestStamp = kUnset;
  2565. for (int32_t l=0; precedenceTable[g][l][0] != -1; ++l) {
  2566. int32_t lineStamp = kUnset;
  2567. // Skip over first entry if it is negative
  2568. for (int32_t i=((precedenceTable[g][l][0]>=kResolveRemap)?1:0); precedenceTable[g][l][i]!=-1; ++i) {
  2569. U_ASSERT(precedenceTable[g][l][i] < UCAL_FIELD_COUNT);
  2570. int32_t s = fStamp[precedenceTable[g][l][i]];
  2571. // If any field is unset then don't use this line
  2572. if (s == kUnset) {
  2573. goto linesInGroup;
  2574. } else if(s > lineStamp) {
  2575. lineStamp = s;
  2576. }
  2577. }
  2578. // Record new maximum stamp & field no.
  2579. if (lineStamp > bestStamp) {
  2580. tempBestField = precedenceTable[g][l][0]; // First field refers to entire line
  2581. if (tempBestField >= kResolveRemap) {
  2582. tempBestField &= (kResolveRemap-1);
  2583. // This check is needed to resolve some issues with UCAL_YEAR precedence mapping
  2584. if (tempBestField != UCAL_DATE || (fStamp[UCAL_WEEK_OF_MONTH] < fStamp[tempBestField])) {
  2585. bestField = tempBestField;
  2586. }
  2587. } else {
  2588. bestField = tempBestField;
  2589. }
  2590. if (bestField == tempBestField) {
  2591. bestStamp = lineStamp;
  2592. }
  2593. }
  2594. linesInGroup:
  2595. ;
  2596. }
  2597. }
  2598. return (UCalendarDateFields)bestField;
  2599. }
  2600. const UFieldResolutionTable Calendar::kDatePrecedence[] =
  2601. {
  2602. {
  2603. { UCAL_DAY_OF_MONTH, kResolveSTOP },
  2604. { UCAL_WEEK_OF_YEAR, UCAL_DAY_OF_WEEK, kResolveSTOP },
  2605. { UCAL_WEEK_OF_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
  2606. { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
  2607. { UCAL_WEEK_OF_YEAR, UCAL_DOW_LOCAL, kResolveSTOP },
  2608. { UCAL_WEEK_OF_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
  2609. { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
  2610. { UCAL_DAY_OF_YEAR, kResolveSTOP },
  2611. { kResolveRemap | UCAL_DAY_OF_MONTH, UCAL_YEAR, kResolveSTOP }, // if YEAR is set over YEAR_WOY use DAY_OF_MONTH
  2612. { kResolveRemap | UCAL_WEEK_OF_YEAR, UCAL_YEAR_WOY, kResolveSTOP }, // if YEAR_WOY is set, calc based on WEEK_OF_YEAR
  2613. { kResolveSTOP }
  2614. },
  2615. {
  2616. { UCAL_WEEK_OF_YEAR, kResolveSTOP },
  2617. { UCAL_WEEK_OF_MONTH, kResolveSTOP },
  2618. { UCAL_DAY_OF_WEEK_IN_MONTH, kResolveSTOP },
  2619. { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
  2620. { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
  2621. { kResolveSTOP }
  2622. },
  2623. {{kResolveSTOP}}
  2624. };
  2625. const UFieldResolutionTable Calendar::kMonthPrecedence[] =
  2626. {
  2627. {
  2628. { UCAL_MONTH,kResolveSTOP, kResolveSTOP },
  2629. { UCAL_ORDINAL_MONTH,kResolveSTOP, kResolveSTOP },
  2630. {kResolveSTOP}
  2631. },
  2632. {{kResolveSTOP}}
  2633. };
  2634. const UFieldResolutionTable Calendar::kDOWPrecedence[] =
  2635. {
  2636. {
  2637. { UCAL_DAY_OF_WEEK,kResolveSTOP, kResolveSTOP },
  2638. { UCAL_DOW_LOCAL,kResolveSTOP, kResolveSTOP },
  2639. {kResolveSTOP}
  2640. },
  2641. {{kResolveSTOP}}
  2642. };
  2643. // precedence for calculating a year
  2644. const UFieldResolutionTable Calendar::kYearPrecedence[] =
  2645. {
  2646. {
  2647. { UCAL_YEAR, kResolveSTOP },
  2648. { UCAL_EXTENDED_YEAR, kResolveSTOP },
  2649. { UCAL_YEAR_WOY, UCAL_WEEK_OF_YEAR, kResolveSTOP }, // YEAR_WOY is useless without WEEK_OF_YEAR
  2650. { kResolveSTOP }
  2651. },
  2652. {{kResolveSTOP}}
  2653. };
  2654. // -------------------------
  2655. void Calendar::computeTime(UErrorCode& status) {
  2656. if (U_FAILURE(status)) {
  2657. return;
  2658. }
  2659. if (!isLenient()) {
  2660. validateFields(status);
  2661. if (U_FAILURE(status)) {
  2662. return;
  2663. }
  2664. }
  2665. // Compute the Julian day
  2666. int32_t julianDay = computeJulianDay();
  2667. double millis = Grego::julianDayToMillis(julianDay);
  2668. #if defined (U_DEBUG_CAL)
  2669. // int32_t julianInsanityCheck = (int32_t)ClockMath::floorDivide(millis, kOneDay);
  2670. // julianInsanityCheck += kEpochStartAsJulianDay;
  2671. // if(1 || julianInsanityCheck != julianDay) {
  2672. // fprintf(stderr, "%s:%d- D'oh- computed jules %d, to mills (%s)%.lf, recomputed %d\n",
  2673. // __FILE__, __LINE__, julianDay, millis<0.0?"NEG":"", millis, julianInsanityCheck);
  2674. // }
  2675. #endif
  2676. double millisInDay;
  2677. // We only use MILLISECONDS_IN_DAY if it has been set by the user.
  2678. // This makes it possible for the caller to set the calendar to a
  2679. // time and call clear(MONTH) to reset the MONTH to January. This
  2680. // is legacy behavior. Without this, clear(MONTH) has no effect,
  2681. // since the internally set JULIAN_DAY is used.
  2682. if (fStamp[UCAL_MILLISECONDS_IN_DAY] >= ((int32_t)kMinimumUserStamp) &&
  2683. newestStamp(UCAL_AM_PM, UCAL_MILLISECOND, kUnset) <= fStamp[UCAL_MILLISECONDS_IN_DAY]) {
  2684. millisInDay = internalGet(UCAL_MILLISECONDS_IN_DAY);
  2685. } else {
  2686. millisInDay = computeMillisInDay();
  2687. }
  2688. UDate t = 0;
  2689. if (fStamp[UCAL_ZONE_OFFSET] >= ((int32_t)kMinimumUserStamp) || fStamp[UCAL_DST_OFFSET] >= ((int32_t)kMinimumUserStamp)) {
  2690. t = millis + millisInDay - (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET));
  2691. } else {
  2692. // Compute the time zone offset and DST offset. There are two potential
  2693. // ambiguities here. We'll assume a 2:00 am (wall time) switchover time
  2694. // for discussion purposes here.
  2695. //
  2696. // 1. The positive offset change such as transition into DST.
  2697. // Here, a designated time of 2:00 am - 2:59 am does not actually exist.
  2698. // For this case, skippedWallTime option specifies the behavior.
  2699. // For example, 2:30 am is interpreted as;
  2700. // - WALLTIME_LAST(default): 3:30 am (DST) (interpreting 2:30 am as 31 minutes after 1:59 am (STD))
  2701. // - WALLTIME_FIRST: 1:30 am (STD) (interpreting 2:30 am as 30 minutes before 3:00 am (DST))
  2702. // - WALLTIME_NEXT_VALID: 3:00 am (DST) (next valid time after 2:30 am on a wall clock)
  2703. // 2. The negative offset change such as transition out of DST.
  2704. // Here, a designated time of 1:00 am - 1:59 am can be in standard or DST. Both are valid
  2705. // representations (the rep jumps from 1:59:59 DST to 1:00:00 Std).
  2706. // For this case, repeatedWallTime option specifies the behavior.
  2707. // For example, 1:30 am is interpreted as;
  2708. // - WALLTIME_LAST(default): 1:30 am (STD) - latter occurrence
  2709. // - WALLTIME_FIRST: 1:30 am (DST) - former occurrence
  2710. //
  2711. // In addition to above, when calendar is strict (not default), wall time falls into
  2712. // the skipped time range will be processed as an error case.
  2713. //
  2714. // These special cases are mostly handled in #computeZoneOffset(long), except WALLTIME_NEXT_VALID
  2715. // at positive offset change. The protected method computeZoneOffset(long) is exposed to Calendar
  2716. // subclass implementations and marked as @stable. Strictly speaking, WALLTIME_NEXT_VALID
  2717. // should be also handled in the same place, but we cannot change the code flow without deprecating
  2718. // the protected method.
  2719. //
  2720. // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
  2721. // or DST_OFFSET fields; then we use those fields.
  2722. if (!isLenient() || fSkippedWallTime == UCAL_WALLTIME_NEXT_VALID) {
  2723. // When strict, invalidate a wall time falls into a skipped wall time range.
  2724. // When lenient and skipped wall time option is WALLTIME_NEXT_VALID,
  2725. // the result time will be adjusted to the next valid time (on wall clock).
  2726. int32_t zoneOffset = computeZoneOffset(millis, millisInDay, status);
  2727. UDate tmpTime = millis + millisInDay - zoneOffset;
  2728. int32_t raw, dst;
  2729. fZone->getOffset(tmpTime, false, raw, dst, status);
  2730. if (U_SUCCESS(status)) {
  2731. // zoneOffset != (raw + dst) only when the given wall time fall into
  2732. // a skipped wall time range caused by positive zone offset transition.
  2733. if (zoneOffset != (raw + dst)) {
  2734. if (!isLenient()) {
  2735. status = U_ILLEGAL_ARGUMENT_ERROR;
  2736. } else {
  2737. U_ASSERT(fSkippedWallTime == UCAL_WALLTIME_NEXT_VALID);
  2738. // Adjust time to the next valid wall clock time.
  2739. // At this point, tmpTime is on or after the zone offset transition causing
  2740. // the skipped time range.
  2741. UDate immediatePrevTransition;
  2742. UBool hasTransition = getImmediatePreviousZoneTransition(tmpTime, &immediatePrevTransition, status);
  2743. if (U_SUCCESS(status) && hasTransition) {
  2744. t = immediatePrevTransition;
  2745. }
  2746. }
  2747. } else {
  2748. t = tmpTime;
  2749. }
  2750. }
  2751. } else {
  2752. t = millis + millisInDay - computeZoneOffset(millis, millisInDay, status);
  2753. }
  2754. }
  2755. if (U_SUCCESS(status)) {
  2756. internalSetTime(t);
  2757. }
  2758. }
  2759. /**
  2760. * Find the previous zone transition near the given time.
  2761. */
  2762. UBool Calendar::getImmediatePreviousZoneTransition(UDate base, UDate *transitionTime, UErrorCode& status) const {
  2763. if (U_FAILURE(status)) {
  2764. return false;
  2765. }
  2766. BasicTimeZone *btz = getBasicTimeZone();
  2767. if (btz) {
  2768. TimeZoneTransition trans;
  2769. UBool hasTransition = btz->getPreviousTransition(base, true, trans);
  2770. if (hasTransition) {
  2771. *transitionTime = trans.getTime();
  2772. return true;
  2773. } else {
  2774. // Could not find any transitions.
  2775. // Note: This should never happen.
  2776. status = U_INTERNAL_PROGRAM_ERROR;
  2777. }
  2778. } else {
  2779. // If not BasicTimeZone, return unsupported error for now.
  2780. // TODO: We may support non-BasicTimeZone in future.
  2781. status = U_UNSUPPORTED_ERROR;
  2782. }
  2783. return false;
  2784. }
  2785. /**
  2786. * Compute the milliseconds in the day from the fields. This is a
  2787. * value from 0 to 23:59:59.999 inclusive, unless fields are out of
  2788. * range, in which case it can be an arbitrary value. This value
  2789. * reflects local zone wall time.
  2790. * @stable ICU 2.0
  2791. */
  2792. double Calendar::computeMillisInDay() {
  2793. // Do the time portion of the conversion.
  2794. double millisInDay = 0;
  2795. // Find the best set of fields specifying the time of day. There
  2796. // are only two possibilities here; the HOUR_OF_DAY or the
  2797. // AM_PM and the HOUR.
  2798. int32_t hourOfDayStamp = fStamp[UCAL_HOUR_OF_DAY];
  2799. int32_t hourStamp = (fStamp[UCAL_HOUR] > fStamp[UCAL_AM_PM])?fStamp[UCAL_HOUR]:fStamp[UCAL_AM_PM];
  2800. int32_t bestStamp = (hourStamp > hourOfDayStamp) ? hourStamp : hourOfDayStamp;
  2801. // Hours
  2802. if (bestStamp != kUnset) {
  2803. if (bestStamp == hourOfDayStamp) {
  2804. // Don't normalize here; let overflow bump into the next period.
  2805. // This is consistent with how we handle other fields.
  2806. millisInDay += internalGet(UCAL_HOUR_OF_DAY);
  2807. } else {
  2808. // Don't normalize here; let overflow bump into the next period.
  2809. // This is consistent with how we handle other fields.
  2810. millisInDay += internalGet(UCAL_HOUR);
  2811. millisInDay += 12 * internalGet(UCAL_AM_PM); // Default works for unset AM_PM
  2812. }
  2813. }
  2814. // We use the fact that unset == 0; we start with millisInDay
  2815. // == HOUR_OF_DAY.
  2816. millisInDay *= 60;
  2817. millisInDay += internalGet(UCAL_MINUTE); // now have minutes
  2818. millisInDay *= 60;
  2819. millisInDay += internalGet(UCAL_SECOND); // now have seconds
  2820. millisInDay *= 1000;
  2821. millisInDay += internalGet(UCAL_MILLISECOND); // now have millis
  2822. return millisInDay;
  2823. }
  2824. /**
  2825. * This method can assume EXTENDED_YEAR has been set.
  2826. * @param millis milliseconds of the date fields
  2827. * @param millisInDay milliseconds of the time fields; may be out
  2828. * or range.
  2829. * @stable ICU 2.0
  2830. */
  2831. int32_t Calendar::computeZoneOffset(double millis, double millisInDay, UErrorCode &ec) {
  2832. if (U_FAILURE(ec)) {
  2833. return 0;
  2834. }
  2835. int32_t rawOffset, dstOffset;
  2836. UDate wall = millis + millisInDay;
  2837. BasicTimeZone* btz = getBasicTimeZone();
  2838. if (btz) {
  2839. UTimeZoneLocalOption duplicatedTimeOpt = (fRepeatedWallTime == UCAL_WALLTIME_FIRST) ? UCAL_TZ_LOCAL_FORMER : UCAL_TZ_LOCAL_LATTER;
  2840. UTimeZoneLocalOption nonExistingTimeOpt = (fSkippedWallTime == UCAL_WALLTIME_FIRST) ? UCAL_TZ_LOCAL_LATTER : UCAL_TZ_LOCAL_FORMER;
  2841. btz->getOffsetFromLocal(wall, nonExistingTimeOpt, duplicatedTimeOpt, rawOffset, dstOffset, ec);
  2842. } else {
  2843. const TimeZone& tz = getTimeZone();
  2844. // By default, TimeZone::getOffset behaves UCAL_WALLTIME_LAST for both.
  2845. tz.getOffset(wall, true, rawOffset, dstOffset, ec);
  2846. UBool sawRecentNegativeShift = false;
  2847. if (fRepeatedWallTime == UCAL_WALLTIME_FIRST) {
  2848. // Check if the given wall time falls into repeated time range
  2849. UDate tgmt = wall - (rawOffset + dstOffset);
  2850. // Any negative zone transition within last 6 hours?
  2851. // Note: The maximum historic negative zone transition is -3 hours in the tz database.
  2852. // 6 hour window would be sufficient for this purpose.
  2853. int32_t tmpRaw, tmpDst;
  2854. tz.getOffset(tgmt - 6*60*60*1000, false, tmpRaw, tmpDst, ec);
  2855. int32_t offsetDelta = (rawOffset + dstOffset) - (tmpRaw + tmpDst);
  2856. U_ASSERT(offsetDelta < -6*60*60*1000);
  2857. if (offsetDelta < 0) {
  2858. sawRecentNegativeShift = true;
  2859. // Negative shift within last 6 hours. When UCAL_WALLTIME_FIRST is used and the given wall time falls
  2860. // into the repeated time range, use offsets before the transition.
  2861. // Note: If it does not fall into the repeated time range, offsets remain unchanged below.
  2862. tz.getOffset(wall + offsetDelta, true, rawOffset, dstOffset, ec);
  2863. }
  2864. }
  2865. if (!sawRecentNegativeShift && fSkippedWallTime == UCAL_WALLTIME_FIRST) {
  2866. // When skipped wall time option is WALLTIME_FIRST,
  2867. // recalculate offsets from the resolved time (non-wall).
  2868. // When the given wall time falls into skipped wall time,
  2869. // the offsets will be based on the zone offsets AFTER
  2870. // the transition (which means, earliest possible interpretation).
  2871. UDate tgmt = wall - (rawOffset + dstOffset);
  2872. tz.getOffset(tgmt, false, rawOffset, dstOffset, ec);
  2873. }
  2874. }
  2875. return rawOffset + dstOffset;
  2876. }
  2877. int32_t Calendar::computeJulianDay()
  2878. {
  2879. // We want to see if any of the date fields is newer than the
  2880. // JULIAN_DAY. If not, then we use JULIAN_DAY. If so, then we do
  2881. // the normal resolution. We only use JULIAN_DAY if it has been
  2882. // set by the user. This makes it possible for the caller to set
  2883. // the calendar to a time and call clear(MONTH) to reset the MONTH
  2884. // to January. This is legacy behavior. Without this,
  2885. // clear(MONTH) has no effect, since the internally set JULIAN_DAY
  2886. // is used.
  2887. if (fStamp[UCAL_JULIAN_DAY] >= (int32_t)kMinimumUserStamp) {
  2888. int32_t bestStamp = newestStamp(UCAL_ERA, UCAL_DAY_OF_WEEK_IN_MONTH, kUnset);
  2889. bestStamp = newestStamp(UCAL_YEAR_WOY, UCAL_EXTENDED_YEAR, bestStamp);
  2890. bestStamp = newestStamp(UCAL_ORDINAL_MONTH, UCAL_ORDINAL_MONTH, bestStamp);
  2891. if (bestStamp <= fStamp[UCAL_JULIAN_DAY]) {
  2892. return internalGet(UCAL_JULIAN_DAY);
  2893. }
  2894. }
  2895. UCalendarDateFields bestField = resolveFields(getFieldResolutionTable());
  2896. if (bestField == UCAL_FIELD_COUNT) {
  2897. bestField = UCAL_DAY_OF_MONTH;
  2898. }
  2899. return handleComputeJulianDay(bestField);
  2900. }
  2901. // -------------------------------------------
  2902. int32_t Calendar::handleComputeJulianDay(UCalendarDateFields bestField) {
  2903. UBool useMonth = (bestField == UCAL_DAY_OF_MONTH ||
  2904. bestField == UCAL_WEEK_OF_MONTH ||
  2905. bestField == UCAL_DAY_OF_WEEK_IN_MONTH);
  2906. int32_t year;
  2907. if (bestField == UCAL_WEEK_OF_YEAR && newerField(UCAL_YEAR_WOY, UCAL_YEAR) == UCAL_YEAR_WOY) {
  2908. year = internalGet(UCAL_YEAR_WOY);
  2909. } else {
  2910. year = handleGetExtendedYear();
  2911. }
  2912. internalSet(UCAL_EXTENDED_YEAR, year);
  2913. #if defined (U_DEBUG_CAL)
  2914. fprintf(stderr, "%s:%d: bestField= %s - y=%d\n", __FILE__, __LINE__, fldName(bestField), year);
  2915. #endif
  2916. // Get the Julian day of the day BEFORE the start of this year.
  2917. // If useMonth is true, get the day before the start of the month.
  2918. // give calendar subclass a chance to have a default 'first' month
  2919. int32_t month;
  2920. if(isSet(UCAL_MONTH) || isSet(UCAL_ORDINAL_MONTH)) {
  2921. month = internalGetMonth();
  2922. } else {
  2923. month = getDefaultMonthInYear(year);
  2924. }
  2925. int32_t julianDay = handleComputeMonthStart(year, useMonth ? month : 0, useMonth);
  2926. if (bestField == UCAL_DAY_OF_MONTH) {
  2927. // give calendar subclass a chance to have a default 'first' dom
  2928. int32_t dayOfMonth;
  2929. if(isSet(UCAL_DAY_OF_MONTH)) {
  2930. dayOfMonth = internalGet(UCAL_DAY_OF_MONTH,1);
  2931. } else {
  2932. dayOfMonth = getDefaultDayInMonth(year, month);
  2933. }
  2934. return julianDay + dayOfMonth;
  2935. }
  2936. if (bestField == UCAL_DAY_OF_YEAR) {
  2937. return julianDay + internalGet(UCAL_DAY_OF_YEAR);
  2938. }
  2939. int32_t firstDayOfWeek = getFirstDayOfWeek(); // Localized fdw
  2940. // At this point julianDay is the 0-based day BEFORE the first day of
  2941. // January 1, year 1 of the given calendar. If julianDay == 0, it
  2942. // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
  2943. // or Gregorian). (or it is before the month we are in, if useMonth is True)
  2944. // At this point we need to process the WEEK_OF_MONTH or
  2945. // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH.
  2946. // First, perform initial shared computations. These locate the
  2947. // first week of the period.
  2948. // Get the 0-based localized DOW of day one of the month or year.
  2949. // Valid range 0..6.
  2950. int32_t first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek;
  2951. if (first < 0) {
  2952. first += 7;
  2953. }
  2954. int32_t dowLocal = getLocalDOW();
  2955. // Find the first target DOW (dowLocal) in the month or year.
  2956. // Actually, it may be just before the first of the month or year.
  2957. // It will be an integer from -5..7.
  2958. int32_t date = 1 - first + dowLocal;
  2959. if (bestField == UCAL_DAY_OF_WEEK_IN_MONTH) {
  2960. // Adjust the target DOW to be in the month or year.
  2961. if (date < 1) {
  2962. date += 7;
  2963. }
  2964. // The only trickiness occurs if the day-of-week-in-month is
  2965. // negative.
  2966. int32_t dim = internalGet(UCAL_DAY_OF_WEEK_IN_MONTH, 1);
  2967. if (dim >= 0) {
  2968. date += 7*(dim - 1);
  2969. } else {
  2970. // Move date to the last of this day-of-week in this month,
  2971. // then back up as needed. If dim==-1, we don't back up at
  2972. // all. If dim==-2, we back up once, etc. Don't back up
  2973. // past the first of the given day-of-week in this month.
  2974. // Note that we handle -2, -3, etc. correctly, even though
  2975. // values < -1 are technically disallowed.
  2976. int32_t m = internalGetMonth(UCAL_JANUARY);
  2977. int32_t monthLength = handleGetMonthLength(year, m);
  2978. date += ((monthLength - date) / 7 + dim + 1) * 7;
  2979. }
  2980. } else {
  2981. #if defined (U_DEBUG_CAL)
  2982. fprintf(stderr, "%s:%d - bf= %s\n", __FILE__, __LINE__, fldName(bestField));
  2983. #endif
  2984. if(bestField == UCAL_WEEK_OF_YEAR) { // ------------------------------------- WOY -------------
  2985. if(!isSet(UCAL_YEAR_WOY) || // YWOY not set at all or
  2986. ( (resolveFields(kYearPrecedence) != UCAL_YEAR_WOY) // YWOY doesn't have precedence
  2987. && (fStamp[UCAL_YEAR_WOY]!=kInternallySet) ) ) // (excluding where all fields are internally set - then YWOY is used)
  2988. {
  2989. // need to be sure to stay in 'real' year.
  2990. int32_t woy = internalGet(bestField);
  2991. int32_t nextJulianDay = handleComputeMonthStart(year+1, 0, false); // jd of day before jan 1
  2992. int32_t nextFirst = julianDayToDayOfWeek(nextJulianDay + 1) - firstDayOfWeek;
  2993. if (nextFirst < 0) { // 0..6 ldow of Jan 1
  2994. nextFirst += 7;
  2995. }
  2996. if(woy==1) { // FIRST WEEK ---------------------------------
  2997. #if defined (U_DEBUG_CAL)
  2998. fprintf(stderr, "%s:%d - woy=%d, yp=%d, nj(%d)=%d, nf=%d", __FILE__, __LINE__,
  2999. internalGet(bestField), resolveFields(kYearPrecedence), year+1,
  3000. nextJulianDay, nextFirst);
  3001. fprintf(stderr, " next: %d DFW, min=%d \n", (7-nextFirst), getMinimalDaysInFirstWeek() );
  3002. #endif
  3003. // nextFirst is now the localized DOW of Jan 1 of y-woy+1
  3004. if((nextFirst > 0) && // Jan 1 starts on FDOW
  3005. (7-nextFirst) >= getMinimalDaysInFirstWeek()) // or enough days in the week
  3006. {
  3007. // Jan 1 of (yearWoy+1) is in yearWoy+1 - recalculate JD to next year
  3008. #if defined (U_DEBUG_CAL)
  3009. fprintf(stderr, "%s:%d - was going to move JD from %d to %d [d%d]\n", __FILE__, __LINE__,
  3010. julianDay, nextJulianDay, (nextJulianDay-julianDay));
  3011. #endif
  3012. julianDay = nextJulianDay;
  3013. // recalculate 'first' [0-based local dow of jan 1]
  3014. first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek;
  3015. if (first < 0) {
  3016. first += 7;
  3017. }
  3018. // recalculate date.
  3019. date = 1 - first + dowLocal;
  3020. }
  3021. } else if(woy>=getLeastMaximum(bestField)) {
  3022. // could be in the last week- find out if this JD would overstep
  3023. int32_t testDate = date;
  3024. if ((7 - first) < getMinimalDaysInFirstWeek()) {
  3025. testDate += 7;
  3026. }
  3027. // Now adjust for the week number.
  3028. testDate += 7 * (woy - 1);
  3029. #if defined (U_DEBUG_CAL)
  3030. fprintf(stderr, "%s:%d - y=%d, y-1=%d doy%d, njd%d (C.F. %d)\n",
  3031. __FILE__, __LINE__, year, year-1, testDate, julianDay+testDate, nextJulianDay);
  3032. #endif
  3033. if(julianDay+testDate > nextJulianDay) { // is it past Dec 31? (nextJulianDay is day BEFORE year+1's Jan 1)
  3034. // Fire up the calculating engines.. retry YWOY = (year-1)
  3035. julianDay = handleComputeMonthStart(year-1, 0, false); // jd before Jan 1 of previous year
  3036. first = julianDayToDayOfWeek(julianDay + 1) - firstDayOfWeek; // 0 based local dow of first week
  3037. if(first < 0) { // 0..6
  3038. first += 7;
  3039. }
  3040. date = 1 - first + dowLocal;
  3041. #if defined (U_DEBUG_CAL)
  3042. fprintf(stderr, "%s:%d - date now %d, jd%d, ywoy%d\n",
  3043. __FILE__, __LINE__, date, julianDay, year-1);
  3044. #endif
  3045. } /* correction needed */
  3046. } /* leastmaximum */
  3047. } /* resolvefields(year) != year_woy */
  3048. } /* bestfield != week_of_year */
  3049. // assert(bestField == WEEK_OF_MONTH || bestField == WEEK_OF_YEAR)
  3050. // Adjust for minimal days in first week
  3051. if ((7 - first) < getMinimalDaysInFirstWeek()) {
  3052. date += 7;
  3053. }
  3054. // Now adjust for the week number.
  3055. date += 7 * (internalGet(bestField) - 1);
  3056. }
  3057. return julianDay + date;
  3058. }
  3059. int32_t
  3060. Calendar::getDefaultMonthInYear(int32_t /*eyear*/)
  3061. {
  3062. return 0;
  3063. }
  3064. int32_t
  3065. Calendar::getDefaultDayInMonth(int32_t /*eyear*/, int32_t /*month*/)
  3066. {
  3067. return 1;
  3068. }
  3069. int32_t Calendar::getLocalDOW()
  3070. {
  3071. // Get zero-based localized DOW, valid range 0..6. This is the DOW
  3072. // we are looking for.
  3073. int32_t dowLocal = 0;
  3074. switch (resolveFields(kDOWPrecedence)) {
  3075. case UCAL_DAY_OF_WEEK:
  3076. dowLocal = internalGet(UCAL_DAY_OF_WEEK) - fFirstDayOfWeek;
  3077. break;
  3078. case UCAL_DOW_LOCAL:
  3079. dowLocal = internalGet(UCAL_DOW_LOCAL) - 1;
  3080. break;
  3081. default:
  3082. break;
  3083. }
  3084. dowLocal = dowLocal % 7;
  3085. if (dowLocal < 0) {
  3086. dowLocal += 7;
  3087. }
  3088. return dowLocal;
  3089. }
  3090. int32_t Calendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy)
  3091. {
  3092. // We have UCAL_YEAR_WOY and UCAL_WEEK_OF_YEAR - from those, determine
  3093. // what year we fall in, so that other code can set it properly.
  3094. // (code borrowed from computeWeekFields and handleComputeJulianDay)
  3095. //return yearWoy;
  3096. // First, we need a reliable DOW.
  3097. UCalendarDateFields bestField = resolveFields(kDatePrecedence); // !! Note: if subclasses have a different table, they should override handleGetExtendedYearFromWeekFields
  3098. // Now, a local DOW
  3099. int32_t dowLocal = getLocalDOW(); // 0..6
  3100. int32_t firstDayOfWeek = getFirstDayOfWeek(); // Localized fdw
  3101. int32_t jan1Start = handleComputeMonthStart(yearWoy, 0, false);
  3102. int32_t nextJan1Start = handleComputeMonthStart(yearWoy+1, 0, false); // next year's Jan1 start
  3103. // At this point julianDay is the 0-based day BEFORE the first day of
  3104. // January 1, year 1 of the given calendar. If julianDay == 0, it
  3105. // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
  3106. // or Gregorian). (or it is before the month we are in, if useMonth is True)
  3107. // At this point we need to process the WEEK_OF_MONTH or
  3108. // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH.
  3109. // First, perform initial shared computations. These locate the
  3110. // first week of the period.
  3111. // Get the 0-based localized DOW of day one of the month or year.
  3112. // Valid range 0..6.
  3113. int32_t first = julianDayToDayOfWeek(jan1Start + 1) - firstDayOfWeek;
  3114. if (first < 0) {
  3115. first += 7;
  3116. }
  3117. //// (nextFirst was not used below)
  3118. // int32_t nextFirst = julianDayToDayOfWeek(nextJan1Start + 1) - firstDayOfWeek;
  3119. // if (nextFirst < 0) {
  3120. // nextFirst += 7;
  3121. //}
  3122. int32_t minDays = getMinimalDaysInFirstWeek();
  3123. UBool jan1InPrevYear = false; // January 1st in the year of WOY is the 1st week? (i.e. first week is < minimal )
  3124. //UBool nextJan1InPrevYear = false; // January 1st of Year of WOY + 1 is in the first week?
  3125. if((7 - first) < minDays) {
  3126. jan1InPrevYear = true;
  3127. }
  3128. // if((7 - nextFirst) < minDays) {
  3129. // nextJan1InPrevYear = true;
  3130. // }
  3131. switch(bestField) {
  3132. case UCAL_WEEK_OF_YEAR:
  3133. if(woy == 1) {
  3134. if(jan1InPrevYear) {
  3135. // the first week of January is in the previous year
  3136. // therefore WOY1 is always solidly within yearWoy
  3137. return yearWoy;
  3138. } else {
  3139. // First WOY is split between two years
  3140. if( dowLocal < first) { // we are prior to Jan 1
  3141. return yearWoy-1; // previous year
  3142. } else {
  3143. return yearWoy; // in this year
  3144. }
  3145. }
  3146. } else if(woy >= getLeastMaximum(bestField)) {
  3147. // we _might_ be in the last week..
  3148. int32_t jd = // Calculate JD of our target day:
  3149. jan1Start + // JD of Jan 1
  3150. (7-first) + // days in the first week (Jan 1.. )
  3151. (woy-1)*7 + // add the weeks of the year
  3152. dowLocal; // the local dow (0..6) of last week
  3153. if(jan1InPrevYear==false) {
  3154. jd -= 7; // woy already includes Jan 1's week.
  3155. }
  3156. if( (jd+1) >= nextJan1Start ) {
  3157. // we are in week 52 or 53 etc. - actual year is yearWoy+1
  3158. return yearWoy+1;
  3159. } else {
  3160. // still in yearWoy;
  3161. return yearWoy;
  3162. }
  3163. } else {
  3164. // we're not possibly in the last week -must be ywoy
  3165. return yearWoy;
  3166. }
  3167. case UCAL_DATE:
  3168. {
  3169. int32_t m = internalGetMonth();
  3170. if((m == 0) &&
  3171. (woy >= getLeastMaximum(UCAL_WEEK_OF_YEAR))) {
  3172. return yearWoy+1; // month 0, late woy = in the next year
  3173. } else if(woy==1) {
  3174. //if(nextJan1InPrevYear) {
  3175. if(m == 0) {
  3176. return yearWoy;
  3177. } else {
  3178. return yearWoy-1;
  3179. }
  3180. //}
  3181. }
  3182. }
  3183. //(internalGet(UCAL_DATE) <= (7-first)) /* && in minDow */ ) {
  3184. //within 1st week and in this month..
  3185. //return yearWoy+1;
  3186. return yearWoy;
  3187. default: // assume the year is appropriate
  3188. return yearWoy;
  3189. }
  3190. }
  3191. int32_t Calendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const
  3192. {
  3193. return handleComputeMonthStart(extendedYear, month+1, true) -
  3194. handleComputeMonthStart(extendedYear, month, true);
  3195. }
  3196. int32_t Calendar::handleGetYearLength(int32_t eyear) const {
  3197. return handleComputeMonthStart(eyear+1, 0, false) -
  3198. handleComputeMonthStart(eyear, 0, false);
  3199. }
  3200. int32_t
  3201. Calendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const
  3202. {
  3203. if (U_FAILURE(status)) {
  3204. return 0;
  3205. }
  3206. int32_t result;
  3207. switch (field) {
  3208. case UCAL_DATE:
  3209. {
  3210. if(U_FAILURE(status)) return 0;
  3211. Calendar *cal = clone();
  3212. if(!cal) { status = U_MEMORY_ALLOCATION_ERROR; return 0; }
  3213. cal->setLenient(true);
  3214. cal->prepareGetActual(field,false,status);
  3215. result = handleGetMonthLength(cal->get(UCAL_EXTENDED_YEAR, status), cal->get(UCAL_MONTH, status));
  3216. delete cal;
  3217. }
  3218. break;
  3219. case UCAL_DAY_OF_YEAR:
  3220. {
  3221. if(U_FAILURE(status)) return 0;
  3222. Calendar *cal = clone();
  3223. if(!cal) { status = U_MEMORY_ALLOCATION_ERROR; return 0; }
  3224. cal->setLenient(true);
  3225. cal->prepareGetActual(field,false,status);
  3226. result = handleGetYearLength(cal->get(UCAL_EXTENDED_YEAR, status));
  3227. delete cal;
  3228. }
  3229. break;
  3230. case UCAL_DAY_OF_WEEK:
  3231. case UCAL_AM_PM:
  3232. case UCAL_HOUR:
  3233. case UCAL_HOUR_OF_DAY:
  3234. case UCAL_MINUTE:
  3235. case UCAL_SECOND:
  3236. case UCAL_MILLISECOND:
  3237. case UCAL_ZONE_OFFSET:
  3238. case UCAL_DST_OFFSET:
  3239. case UCAL_DOW_LOCAL:
  3240. case UCAL_JULIAN_DAY:
  3241. case UCAL_MILLISECONDS_IN_DAY:
  3242. // These fields all have fixed minima/maxima
  3243. result = getMaximum(field);
  3244. break;
  3245. case UCAL_ORDINAL_MONTH:
  3246. result = inTemporalLeapYear(status) ? getMaximum(UCAL_ORDINAL_MONTH) : getLeastMaximum(UCAL_ORDINAL_MONTH);
  3247. break;
  3248. default:
  3249. // For all other fields, do it the hard way....
  3250. result = getActualHelper(field, getLeastMaximum(field), getMaximum(field),status);
  3251. break;
  3252. }
  3253. return result;
  3254. }
  3255. /**
  3256. * Prepare this calendar for computing the actual minimum or maximum.
  3257. * This method modifies this calendar's fields; it is called on a
  3258. * temporary calendar.
  3259. *
  3260. * <p>Rationale: The semantics of getActualXxx() is to return the
  3261. * maximum or minimum value that the given field can take, taking into
  3262. * account other relevant fields. In general these other fields are
  3263. * larger fields. For example, when computing the actual maximum
  3264. * DATE, the current value of DATE itself is ignored,
  3265. * as is the value of any field smaller.
  3266. *
  3267. * <p>The time fields all have fixed minima and maxima, so we don't
  3268. * need to worry about them. This also lets us set the
  3269. * MILLISECONDS_IN_DAY to zero to erase any effects the time fields
  3270. * might have when computing date fields.
  3271. *
  3272. * <p>DAY_OF_WEEK is adjusted specially for the WEEK_OF_MONTH and
  3273. * WEEK_OF_YEAR fields to ensure that they are computed correctly.
  3274. * @internal
  3275. */
  3276. void Calendar::prepareGetActual(UCalendarDateFields field, UBool isMinimum, UErrorCode &status)
  3277. {
  3278. if (U_FAILURE(status)) {
  3279. return;
  3280. }
  3281. set(UCAL_MILLISECONDS_IN_DAY, 0);
  3282. switch (field) {
  3283. case UCAL_YEAR:
  3284. case UCAL_EXTENDED_YEAR:
  3285. set(UCAL_DAY_OF_YEAR, getGreatestMinimum(UCAL_DAY_OF_YEAR));
  3286. break;
  3287. case UCAL_YEAR_WOY:
  3288. set(UCAL_WEEK_OF_YEAR, getGreatestMinimum(UCAL_WEEK_OF_YEAR));
  3289. U_FALLTHROUGH;
  3290. case UCAL_MONTH:
  3291. set(UCAL_DATE, getGreatestMinimum(UCAL_DATE));
  3292. break;
  3293. case UCAL_DAY_OF_WEEK_IN_MONTH:
  3294. // For dowim, the maximum occurs for the DOW of the first of the
  3295. // month.
  3296. set(UCAL_DATE, 1);
  3297. set(UCAL_DAY_OF_WEEK, get(UCAL_DAY_OF_WEEK, status)); // Make this user set
  3298. break;
  3299. case UCAL_WEEK_OF_MONTH:
  3300. case UCAL_WEEK_OF_YEAR:
  3301. // If we're counting weeks, set the day of the week to either the
  3302. // first or last localized DOW. We know the last week of a month
  3303. // or year will contain the first day of the week, and that the
  3304. // first week will contain the last DOW.
  3305. {
  3306. int32_t dow = fFirstDayOfWeek;
  3307. if (isMinimum) {
  3308. dow = (dow + 6) % 7; // set to last DOW
  3309. if (dow < UCAL_SUNDAY) {
  3310. dow += 7;
  3311. }
  3312. }
  3313. #if defined (U_DEBUG_CAL)
  3314. fprintf(stderr, "prepareGetActualHelper(WOM/WOY) - dow=%d\n", dow);
  3315. #endif
  3316. set(UCAL_DAY_OF_WEEK, dow);
  3317. }
  3318. break;
  3319. default:
  3320. break;
  3321. }
  3322. // Do this last to give it the newest time stamp
  3323. set(field, getGreatestMinimum(field));
  3324. }
  3325. int32_t Calendar::getActualHelper(UCalendarDateFields field, int32_t startValue, int32_t endValue, UErrorCode &status) const
  3326. {
  3327. #if defined (U_DEBUG_CAL)
  3328. fprintf(stderr, "getActualHelper(%d,%d .. %d, %s)\n", field, startValue, endValue, u_errorName(status));
  3329. #endif
  3330. if (U_FAILURE(status)) {
  3331. return 0;
  3332. }
  3333. if (startValue == endValue) {
  3334. // if we know that the maximum value is always the same, just return it
  3335. return startValue;
  3336. }
  3337. int32_t delta = (endValue > startValue) ? 1 : -1;
  3338. // clone the calendar so we don't mess with the real one, and set it to
  3339. // accept anything for the field values
  3340. if(U_FAILURE(status)) return startValue;
  3341. Calendar *work = clone();
  3342. if(!work) { status = U_MEMORY_ALLOCATION_ERROR; return startValue; }
  3343. // need to resolve time here, otherwise, fields set for actual limit
  3344. // may cause conflict with fields previously set (but not yet resolved).
  3345. work->complete(status);
  3346. work->setLenient(true);
  3347. work->prepareGetActual(field, delta < 0, status);
  3348. // now try each value from the start to the end one by one until
  3349. // we get a value that normalizes to another value. The last value that
  3350. // normalizes to itself is the actual maximum for the current date
  3351. work->set(field, startValue);
  3352. // prepareGetActual sets the first day of week in the same week with
  3353. // the first day of a month. Unlike WEEK_OF_YEAR, week number for the
  3354. // week which contains days from both previous and current month is
  3355. // not unique. For example, last several days in the previous month
  3356. // is week 5, and the rest of week is week 1.
  3357. int32_t result = startValue;
  3358. if ((work->get(field, status) != startValue
  3359. && field != UCAL_WEEK_OF_MONTH && delta > 0 ) || U_FAILURE(status)) {
  3360. #if defined (U_DEBUG_CAL)
  3361. fprintf(stderr, "getActualHelper(fld %d) - got %d (not %d) - %s\n", field, work->get(field,status), startValue, u_errorName(status));
  3362. #endif
  3363. } else {
  3364. do {
  3365. startValue += delta;
  3366. work->add(field, delta, status);
  3367. if (work->get(field, status) != startValue || U_FAILURE(status)) {
  3368. #if defined (U_DEBUG_CAL)
  3369. fprintf(stderr, "getActualHelper(fld %d) - got %d (not %d), BREAK - %s\n", field, work->get(field,status), startValue, u_errorName(status));
  3370. #endif
  3371. break;
  3372. }
  3373. result = startValue;
  3374. } while (startValue != endValue);
  3375. }
  3376. delete work;
  3377. #if defined (U_DEBUG_CAL)
  3378. fprintf(stderr, "getActualHelper(%d) = %d\n", field, result);
  3379. #endif
  3380. return result;
  3381. }
  3382. // -------------------------------------
  3383. void
  3384. Calendar::setWeekData(const Locale& desiredLocale, const char *type, UErrorCode& status)
  3385. {
  3386. if (U_FAILURE(status)) return;
  3387. fFirstDayOfWeek = UCAL_SUNDAY;
  3388. fMinimalDaysInFirstWeek = 1;
  3389. fWeekendOnset = UCAL_SATURDAY;
  3390. fWeekendOnsetMillis = 0;
  3391. fWeekendCease = UCAL_SUNDAY;
  3392. fWeekendCeaseMillis = 86400000; // 24*60*60*1000
  3393. // Since week and weekend data is territory based instead of language based,
  3394. // we may need to tweak the locale that we are using to try to get the appropriate
  3395. // values, using the following logic:
  3396. // 1). If the locale has a language but no territory, use the territory as defined by
  3397. // the likely subtags.
  3398. // 2). If the locale has a script designation then we ignore it,
  3399. // then remove it ( i.e. "en_Latn_US" becomes "en_US" )
  3400. UErrorCode myStatus = U_ZERO_ERROR;
  3401. Locale min(desiredLocale);
  3402. min.minimizeSubtags(myStatus);
  3403. Locale useLocale;
  3404. if ( uprv_strlen(desiredLocale.getCountry()) == 0 ||
  3405. (uprv_strlen(desiredLocale.getScript()) > 0 && uprv_strlen(min.getScript()) == 0) ) {
  3406. myStatus = U_ZERO_ERROR;
  3407. Locale max(desiredLocale);
  3408. max.addLikelySubtags(myStatus);
  3409. useLocale = Locale(max.getLanguage(),max.getCountry());
  3410. } else {
  3411. useLocale = desiredLocale;
  3412. }
  3413. /* The code here is somewhat of a hack, since week data and weekend data aren't really tied to
  3414. a specific calendar, they aren't truly locale data. But this is the only place where valid and
  3415. actual locale can be set, so we take a shot at it here by loading a representative resource
  3416. from the calendar data. The code used to use the dateTimeElements resource to get first day
  3417. of week data, but this was moved to supplemental data under ticket 7755. (JCE) */
  3418. // Get the monthNames resource bundle for the calendar 'type'. Fallback to gregorian if the resource is not
  3419. // found.
  3420. LocalUResourceBundlePointer calData(ures_open(nullptr, useLocale.getBaseName(), &status));
  3421. ures_getByKey(calData.getAlias(), gCalendar, calData.getAlias(), &status);
  3422. LocalUResourceBundlePointer monthNames;
  3423. if (type != nullptr && *type != '\0' && uprv_strcmp(type, gGregorian) != 0) {
  3424. monthNames.adoptInstead(ures_getByKeyWithFallback(calData.getAlias(), type, nullptr, &status));
  3425. ures_getByKeyWithFallback(monthNames.getAlias(), gMonthNames,
  3426. monthNames.getAlias(), &status);
  3427. }
  3428. if (monthNames.isNull() || status == U_MISSING_RESOURCE_ERROR) {
  3429. status = U_ZERO_ERROR;
  3430. monthNames.adoptInstead(ures_getByKeyWithFallback(calData.getAlias(), gGregorian,
  3431. monthNames.orphan(), &status));
  3432. ures_getByKeyWithFallback(monthNames.getAlias(), gMonthNames,
  3433. monthNames.getAlias(), &status);
  3434. }
  3435. if (U_SUCCESS(status)) {
  3436. U_LOCALE_BASED(locBased,*this);
  3437. locBased.setLocaleIDs(ures_getLocaleByType(monthNames.getAlias(), ULOC_VALID_LOCALE, &status),
  3438. ures_getLocaleByType(monthNames.getAlias(), ULOC_ACTUAL_LOCALE, &status));
  3439. } else {
  3440. status = U_USING_FALLBACK_WARNING;
  3441. return;
  3442. }
  3443. char region[ULOC_COUNTRY_CAPACITY];
  3444. (void)ulocimp_getRegionForSupplementalData(desiredLocale.getName(), true, region, sizeof(region), &status);
  3445. // Read week data values from supplementalData week data
  3446. UResourceBundle *rb = ures_openDirect(nullptr, "supplementalData", &status);
  3447. ures_getByKey(rb, "weekData", rb, &status);
  3448. UResourceBundle *weekData = ures_getByKey(rb, region, nullptr, &status);
  3449. if (status == U_MISSING_RESOURCE_ERROR && rb != nullptr) {
  3450. status = U_ZERO_ERROR;
  3451. weekData = ures_getByKey(rb, "001", nullptr, &status);
  3452. }
  3453. if (U_FAILURE(status)) {
  3454. status = U_USING_FALLBACK_WARNING;
  3455. } else {
  3456. int32_t arrLen;
  3457. const int32_t *weekDataArr = ures_getIntVector(weekData,&arrLen,&status);
  3458. if( U_SUCCESS(status) && arrLen == 6
  3459. && 1 <= weekDataArr[0] && weekDataArr[0] <= 7
  3460. && 1 <= weekDataArr[1] && weekDataArr[1] <= 7
  3461. && 1 <= weekDataArr[2] && weekDataArr[2] <= 7
  3462. && 1 <= weekDataArr[4] && weekDataArr[4] <= 7) {
  3463. fFirstDayOfWeek = (UCalendarDaysOfWeek)weekDataArr[0];
  3464. fMinimalDaysInFirstWeek = (uint8_t)weekDataArr[1];
  3465. fWeekendOnset = (UCalendarDaysOfWeek)weekDataArr[2];
  3466. fWeekendOnsetMillis = weekDataArr[3];
  3467. fWeekendCease = (UCalendarDaysOfWeek)weekDataArr[4];
  3468. fWeekendCeaseMillis = weekDataArr[5];
  3469. } else {
  3470. status = U_INVALID_FORMAT_ERROR;
  3471. }
  3472. // Check if the locale has a "fw" u extension and we honor it if present.
  3473. // And we don't change the overal status, as the presence / lack of "fw" is not an error.
  3474. UErrorCode fwStatus = U_ZERO_ERROR;
  3475. char fwExt[ULOC_FULLNAME_CAPACITY] = "";
  3476. desiredLocale.getKeywordValue("fw", fwExt, ULOC_FULLNAME_CAPACITY, fwStatus);
  3477. if (U_SUCCESS(fwStatus)) {
  3478. if (uprv_strcmp(fwExt, "sun") == 0) {
  3479. fFirstDayOfWeek = UCAL_SUNDAY;
  3480. } else if (uprv_strcmp(fwExt, "mon") == 0) {
  3481. fFirstDayOfWeek = UCAL_MONDAY;
  3482. } else if (uprv_strcmp(fwExt, "tue") == 0) {
  3483. fFirstDayOfWeek = UCAL_TUESDAY;
  3484. } else if (uprv_strcmp(fwExt, "wed") == 0) {
  3485. fFirstDayOfWeek = UCAL_WEDNESDAY;
  3486. } else if (uprv_strcmp(fwExt, "thu") == 0) {
  3487. fFirstDayOfWeek = UCAL_THURSDAY;
  3488. } else if (uprv_strcmp(fwExt, "fri") == 0) {
  3489. fFirstDayOfWeek = UCAL_FRIDAY;
  3490. } else if (uprv_strcmp(fwExt, "sat") == 0) {
  3491. fFirstDayOfWeek = UCAL_SATURDAY;
  3492. }
  3493. }
  3494. }
  3495. ures_close(weekData);
  3496. ures_close(rb);
  3497. }
  3498. /**
  3499. * Recompute the time and update the status fields isTimeSet
  3500. * and areFieldsSet. Callers should check isTimeSet and only
  3501. * call this method if isTimeSet is false.
  3502. */
  3503. void
  3504. Calendar::updateTime(UErrorCode& status)
  3505. {
  3506. computeTime(status);
  3507. if(U_FAILURE(status))
  3508. return;
  3509. // If we are lenient, we need to recompute the fields to normalize
  3510. // the values. Also, if we haven't set all the fields yet (i.e.,
  3511. // in a newly-created object), we need to fill in the fields. [LIU]
  3512. if (isLenient() || ! fAreAllFieldsSet)
  3513. fAreFieldsSet = false;
  3514. fIsTimeSet = true;
  3515. fAreFieldsVirtuallySet = false;
  3516. }
  3517. Locale
  3518. Calendar::getLocale(ULocDataLocaleType type, UErrorCode& status) const {
  3519. U_LOCALE_BASED(locBased, *this);
  3520. return locBased.getLocale(type, status);
  3521. }
  3522. const char *
  3523. Calendar::getLocaleID(ULocDataLocaleType type, UErrorCode& status) const {
  3524. U_LOCALE_BASED(locBased, *this);
  3525. return locBased.getLocaleID(type, status);
  3526. }
  3527. void
  3528. Calendar::recalculateStamp() {
  3529. int32_t index;
  3530. int32_t currentValue;
  3531. int32_t j, i;
  3532. fNextStamp = 1;
  3533. for (j = 0; j < UCAL_FIELD_COUNT; j++) {
  3534. currentValue = STAMP_MAX;
  3535. index = -1;
  3536. for (i = 0; i < UCAL_FIELD_COUNT; i++) {
  3537. if (fStamp[i] > fNextStamp && fStamp[i] < currentValue) {
  3538. currentValue = fStamp[i];
  3539. index = i;
  3540. }
  3541. }
  3542. if (index >= 0) {
  3543. fStamp[index] = ++fNextStamp;
  3544. } else {
  3545. break;
  3546. }
  3547. }
  3548. fNextStamp++;
  3549. }
  3550. // Deprecated function. This doesn't need to be inline.
  3551. void
  3552. Calendar::internalSet(EDateFields field, int32_t value)
  3553. {
  3554. internalSet((UCalendarDateFields) field, value);
  3555. }
  3556. int32_t Calendar::internalGetMonth() const {
  3557. if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
  3558. return internalGet(UCAL_MONTH);
  3559. }
  3560. return internalGet(UCAL_ORDINAL_MONTH);
  3561. }
  3562. int32_t Calendar::internalGetMonth(int32_t defaultValue) const {
  3563. if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
  3564. return internalGet(UCAL_MONTH, defaultValue);
  3565. }
  3566. return internalGet(UCAL_ORDINAL_MONTH);
  3567. }
  3568. BasicTimeZone*
  3569. Calendar::getBasicTimeZone() const {
  3570. if (dynamic_cast<const OlsonTimeZone *>(fZone) != nullptr
  3571. || dynamic_cast<const SimpleTimeZone *>(fZone) != nullptr
  3572. || dynamic_cast<const RuleBasedTimeZone *>(fZone) != nullptr
  3573. || dynamic_cast<const VTimeZone *>(fZone) != nullptr) {
  3574. return (BasicTimeZone*)fZone;
  3575. }
  3576. return nullptr;
  3577. }
  3578. U_NAMESPACE_END
  3579. #endif /* #if !UCONFIG_NO_FORMATTING */
  3580. //eof