Calendar.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.Serialization;
  6. namespace System.Globalization
  7. {
  8. // This abstract class represents a calendar. A calendar reckons time in
  9. // divisions such as weeks, months and years. The number, length and start of
  10. // the divisions vary in each calendar.
  11. //
  12. // Any instant in time can be represented as an n-tuple of numeric values using
  13. // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
  14. // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
  15. // Calendar can map any DateTime value to such an n-tuple and vice versa. The
  16. // DateTimeFormat class can map between such n-tuples and a textual
  17. // representation such as "8:46 AM March 20th 1999 AD".
  18. //
  19. // Most calendars identify a year which begins the current era. There may be any
  20. // number of previous eras. The Calendar class identifies the eras as enumerated
  21. // integers where the current era (CurrentEra) has the value zero.
  22. //
  23. // For consistency, the first unit in each interval, e.g. the first month, is
  24. // assigned the value one.
  25. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
  26. // since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
  27. public abstract class Calendar : ICloneable
  28. {
  29. // Number of 100ns (10E-7 second) ticks per time unit
  30. internal const long TicksPerMillisecond = 10000;
  31. internal const long TicksPerSecond = TicksPerMillisecond * 1000;
  32. internal const long TicksPerMinute = TicksPerSecond * 60;
  33. internal const long TicksPerHour = TicksPerMinute * 60;
  34. internal const long TicksPerDay = TicksPerHour * 24;
  35. // Number of milliseconds per time unit
  36. internal const int MillisPerSecond = 1000;
  37. internal const int MillisPerMinute = MillisPerSecond * 60;
  38. internal const int MillisPerHour = MillisPerMinute * 60;
  39. internal const int MillisPerDay = MillisPerHour * 24;
  40. // Number of days in a non-leap year
  41. internal const int DaysPerYear = 365;
  42. // Number of days in 4 years
  43. internal const int DaysPer4Years = DaysPerYear * 4 + 1;
  44. // Number of days in 100 years
  45. internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
  46. // Number of days in 400 years
  47. internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
  48. // Number of days from 1/1/0001 to 1/1/10000
  49. internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
  50. internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
  51. private int _currentEraValue = -1;
  52. private bool _isReadOnly = false;
  53. // The minimum supported DateTime range for the calendar.
  54. public virtual DateTime MinSupportedDateTime
  55. {
  56. get
  57. {
  58. return (DateTime.MinValue);
  59. }
  60. }
  61. // The maximum supported DateTime range for the calendar.
  62. public virtual DateTime MaxSupportedDateTime
  63. {
  64. get
  65. {
  66. return (DateTime.MaxValue);
  67. }
  68. }
  69. public virtual CalendarAlgorithmType AlgorithmType
  70. {
  71. get
  72. {
  73. return CalendarAlgorithmType.Unknown;
  74. }
  75. }
  76. protected Calendar()
  77. {
  78. //Do-nothing constructor.
  79. }
  80. ///
  81. // This can not be abstract, otherwise no one can create a subclass of Calendar.
  82. //
  83. internal virtual CalendarId ID
  84. {
  85. get
  86. {
  87. return CalendarId.UNINITIALIZED_VALUE;
  88. }
  89. }
  90. ///
  91. // Return the Base calendar ID for calendars that didn't have defined data in calendarData
  92. //
  93. internal virtual CalendarId BaseCalendarID
  94. {
  95. get { return ID; }
  96. }
  97. ////////////////////////////////////////////////////////////////////////
  98. //
  99. // IsReadOnly
  100. //
  101. // Detect if the object is readonly.
  102. //
  103. ////////////////////////////////////////////////////////////////////////
  104. public bool IsReadOnly
  105. {
  106. get { return (_isReadOnly); }
  107. }
  108. ////////////////////////////////////////////////////////////////////////
  109. //
  110. // Clone
  111. //
  112. // Is the implementation of ICloneable.
  113. //
  114. ////////////////////////////////////////////////////////////////////////
  115. public virtual object Clone()
  116. {
  117. object o = MemberwiseClone();
  118. ((Calendar)o).SetReadOnlyState(false);
  119. return (o);
  120. }
  121. ////////////////////////////////////////////////////////////////////////
  122. //
  123. // ReadOnly
  124. //
  125. // Create a cloned readonly instance or return the input one if it is
  126. // readonly.
  127. //
  128. ////////////////////////////////////////////////////////////////////////
  129. public static Calendar ReadOnly(Calendar calendar)
  130. {
  131. if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
  132. if (calendar.IsReadOnly) { return (calendar); }
  133. Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
  134. clonedCalendar.SetReadOnlyState(true);
  135. return (clonedCalendar);
  136. }
  137. internal void VerifyWritable()
  138. {
  139. if (_isReadOnly)
  140. {
  141. throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
  142. }
  143. }
  144. internal void SetReadOnlyState(bool readOnly)
  145. {
  146. _isReadOnly = readOnly;
  147. }
  148. /*=================================CurrentEraValue==========================
  149. **Action: This is used to convert CurrentEra(0) to an appropriate era value.
  150. **Returns:
  151. **Arguments:
  152. **Exceptions:
  153. **Notes:
  154. ** The value is from calendar.nlp.
  155. ============================================================================*/
  156. internal virtual int CurrentEraValue
  157. {
  158. get
  159. {
  160. // The following code assumes that the current era value can not be -1.
  161. if (_currentEraValue == -1)
  162. {
  163. Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
  164. _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
  165. }
  166. return (_currentEraValue);
  167. }
  168. }
  169. // The current era for a calendar.
  170. public const int CurrentEra = 0;
  171. internal int twoDigitYearMax = -1;
  172. internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
  173. {
  174. if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
  175. {
  176. throw new ArgumentException(
  177. string.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
  178. minValue, maxValue)));
  179. }
  180. }
  181. internal DateTime Add(DateTime time, double value, int scale)
  182. {
  183. // From ECMA CLI spec, Partition III, section 3.27:
  184. //
  185. // If overflow occurs converting a floating-point type to an integer, or if the floating-point value
  186. // being converted to an integer is a NaN, the value returned is unspecified.
  187. //
  188. // Based upon this, this method should be performing the comparison against the double
  189. // before attempting a cast. Otherwise, the result is undefined.
  190. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
  191. if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
  192. {
  193. throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
  194. }
  195. long millis = (long)tempMillis;
  196. long ticks = time.Ticks + millis * TicksPerMillisecond;
  197. CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
  198. return (new DateTime(ticks));
  199. }
  200. // Returns the DateTime resulting from adding the given number of
  201. // milliseconds to the specified DateTime. The result is computed by rounding
  202. // the number of milliseconds given by value to the nearest integer,
  203. // and adding that interval to the specified DateTime. The value
  204. // argument is permitted to be negative.
  205. //
  206. public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
  207. {
  208. return (Add(time, milliseconds, 1));
  209. }
  210. // Returns the DateTime resulting from adding a fractional number of
  211. // days to the specified DateTime. The result is computed by rounding the
  212. // fractional number of days given by value to the nearest
  213. // millisecond, and adding that interval to the specified DateTime. The
  214. // value argument is permitted to be negative.
  215. //
  216. public virtual DateTime AddDays(DateTime time, int days)
  217. {
  218. return (Add(time, days, MillisPerDay));
  219. }
  220. // Returns the DateTime resulting from adding a fractional number of
  221. // hours to the specified DateTime. The result is computed by rounding the
  222. // fractional number of hours given by value to the nearest
  223. // millisecond, and adding that interval to the specified DateTime. The
  224. // value argument is permitted to be negative.
  225. //
  226. public virtual DateTime AddHours(DateTime time, int hours)
  227. {
  228. return (Add(time, hours, MillisPerHour));
  229. }
  230. // Returns the DateTime resulting from adding a fractional number of
  231. // minutes to the specified DateTime. The result is computed by rounding the
  232. // fractional number of minutes given by value to the nearest
  233. // millisecond, and adding that interval to the specified DateTime. The
  234. // value argument is permitted to be negative.
  235. //
  236. public virtual DateTime AddMinutes(DateTime time, int minutes)
  237. {
  238. return (Add(time, minutes, MillisPerMinute));
  239. }
  240. // Returns the DateTime resulting from adding the given number of
  241. // months to the specified DateTime. The result is computed by incrementing
  242. // (or decrementing) the year and month parts of the specified DateTime by
  243. // value months, and, if required, adjusting the day part of the
  244. // resulting date downwards to the last day of the resulting month in the
  245. // resulting year. The time-of-day part of the result is the same as the
  246. // time-of-day part of the specified DateTime.
  247. //
  248. // In more precise terms, considering the specified DateTime to be of the
  249. // form y / m / d + t, where y is the
  250. // year, m is the month, d is the day, and t is the
  251. // time-of-day, the result is y1 / m1 / d1 + t,
  252. // where y1 and m1 are computed by adding value months
  253. // to y and m, and d1 is the largest value less than
  254. // or equal to d that denotes a valid day in month m1 of year
  255. // y1.
  256. //
  257. public abstract DateTime AddMonths(DateTime time, int months);
  258. // Returns the DateTime resulting from adding a number of
  259. // seconds to the specified DateTime. The result is computed by rounding the
  260. // fractional number of seconds given by value to the nearest
  261. // millisecond, and adding that interval to the specified DateTime. The
  262. // value argument is permitted to be negative.
  263. //
  264. public virtual DateTime AddSeconds(DateTime time, int seconds)
  265. {
  266. return Add(time, seconds, MillisPerSecond);
  267. }
  268. // Returns the DateTime resulting from adding a number of
  269. // weeks to the specified DateTime. The
  270. // value argument is permitted to be negative.
  271. //
  272. public virtual DateTime AddWeeks(DateTime time, int weeks)
  273. {
  274. return (AddDays(time, weeks * 7));
  275. }
  276. // Returns the DateTime resulting from adding the given number of
  277. // years to the specified DateTime. The result is computed by incrementing
  278. // (or decrementing) the year part of the specified DateTime by value
  279. // years. If the month and day of the specified DateTime is 2/29, and if the
  280. // resulting year is not a leap year, the month and day of the resulting
  281. // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
  282. // parts of the result are the same as those of the specified DateTime.
  283. //
  284. public abstract DateTime AddYears(DateTime time, int years);
  285. // Returns the day-of-month part of the specified DateTime. The returned
  286. // value is an integer between 1 and 31.
  287. //
  288. public abstract int GetDayOfMonth(DateTime time);
  289. // Returns the day-of-week part of the specified DateTime. The returned value
  290. // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
  291. // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
  292. // Thursday, 5 indicates Friday, and 6 indicates Saturday.
  293. //
  294. public abstract DayOfWeek GetDayOfWeek(DateTime time);
  295. // Returns the day-of-year part of the specified DateTime. The returned value
  296. // is an integer between 1 and 366.
  297. //
  298. public abstract int GetDayOfYear(DateTime time);
  299. // Returns the number of days in the month given by the year and
  300. // month arguments.
  301. //
  302. public virtual int GetDaysInMonth(int year, int month)
  303. {
  304. return (GetDaysInMonth(year, month, CurrentEra));
  305. }
  306. // Returns the number of days in the month given by the year and
  307. // month arguments for the specified era.
  308. //
  309. public abstract int GetDaysInMonth(int year, int month, int era);
  310. // Returns the number of days in the year given by the year argument for the current era.
  311. //
  312. public virtual int GetDaysInYear(int year)
  313. {
  314. return (GetDaysInYear(year, CurrentEra));
  315. }
  316. // Returns the number of days in the year given by the year argument for the current era.
  317. //
  318. public abstract int GetDaysInYear(int year, int era);
  319. // Returns the era for the specified DateTime value.
  320. public abstract int GetEra(DateTime time);
  321. /*=================================Eras==========================
  322. **Action: Get the list of era values.
  323. **Returns: The int array of the era names supported in this calendar.
  324. ** null if era is not used.
  325. **Arguments: None.
  326. **Exceptions: None.
  327. ============================================================================*/
  328. public abstract int[] Eras
  329. {
  330. get;
  331. }
  332. // Returns the hour part of the specified DateTime. The returned value is an
  333. // integer between 0 and 23.
  334. //
  335. public virtual int GetHour(DateTime time)
  336. {
  337. return ((int)((time.Ticks / TicksPerHour) % 24));
  338. }
  339. // Returns the millisecond part of the specified DateTime. The returned value
  340. // is an integer between 0 and 999.
  341. //
  342. public virtual double GetMilliseconds(DateTime time)
  343. {
  344. return (double)((time.Ticks / TicksPerMillisecond) % 1000);
  345. }
  346. // Returns the minute part of the specified DateTime. The returned value is
  347. // an integer between 0 and 59.
  348. //
  349. public virtual int GetMinute(DateTime time)
  350. {
  351. return ((int)((time.Ticks / TicksPerMinute) % 60));
  352. }
  353. // Returns the month part of the specified DateTime. The returned value is an
  354. // integer between 1 and 12.
  355. //
  356. public abstract int GetMonth(DateTime time);
  357. // Returns the number of months in the specified year in the current era.
  358. public virtual int GetMonthsInYear(int year)
  359. {
  360. return (GetMonthsInYear(year, CurrentEra));
  361. }
  362. // Returns the number of months in the specified year and era.
  363. public abstract int GetMonthsInYear(int year, int era);
  364. // Returns the second part of the specified DateTime. The returned value is
  365. // an integer between 0 and 59.
  366. //
  367. public virtual int GetSecond(DateTime time)
  368. {
  369. return ((int)((time.Ticks / TicksPerSecond) % 60));
  370. }
  371. /*=================================GetFirstDayWeekOfYear==========================
  372. **Action: Get the week of year using the FirstDay rule.
  373. **Returns: the week of year.
  374. **Arguments:
  375. ** time
  376. ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
  377. **Notes:
  378. ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
  379. ** Assume f is the specifed firstDayOfWeek,
  380. ** and n is the day of week for January 1 of the specified year.
  381. ** Assign offset = n - f;
  382. ** Case 1: offset = 0
  383. ** E.g.
  384. ** f=1
  385. ** weekday 0 1 2 3 4 5 6 0 1
  386. ** date 1/1
  387. ** week# 1 2
  388. ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
  389. **
  390. ** Case 2: offset < 0
  391. ** e.g.
  392. ** n=1 f=3
  393. ** weekday 0 1 2 3 4 5 6 0
  394. ** date 1/1
  395. ** week# 1 2
  396. ** This means that the first week actually starts 5 days before 1/1.
  397. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
  398. ** Case 3: offset > 0
  399. ** e.g.
  400. ** f=0 n=2
  401. ** weekday 0 1 2 3 4 5 6 0 1 2
  402. ** date 1/1
  403. ** week# 1 2
  404. ** This means that the first week actually starts 2 days before 1/1.
  405. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
  406. ============================================================================*/
  407. internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
  408. {
  409. int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
  410. // Calculate the day of week for the first day of the year.
  411. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
  412. // this value can be less than 0. It's fine since we are making it positive again in calculating offset.
  413. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
  414. int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
  415. Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
  416. return ((dayOfYear + offset) / 7 + 1);
  417. }
  418. private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
  419. {
  420. int dayForJan1;
  421. int offset;
  422. int day;
  423. int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
  424. //
  425. // Calculate the number of days between the first day of year (1/1) and the first day of the week.
  426. // This value will be a positive value from 0 ~ 6. We call this value as "offset".
  427. //
  428. // If offset is 0, it means that the 1/1 is the start of the first week.
  429. // Assume the first day of the week is Monday, it will look like this:
  430. // Sun Mon Tue Wed Thu Fri Sat
  431. // 12/31 1/1 1/2 1/3 1/4 1/5 1/6
  432. // +--> First week starts here.
  433. //
  434. // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
  435. // Assume the first day of the week is Monday, it will look like this:
  436. // Sun Mon Tue Wed Thu Fri Sat
  437. // 1/1 1/2 1/3 1/4 1/5 1/6 1/7
  438. // +--> First week starts here.
  439. //
  440. // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
  441. // Assume the first day of the week is Monday, it will look like this:
  442. // Sat Sun Mon Tue Wed Thu Fri Sat
  443. // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
  444. // +--> First week starts here.
  445. // Day of week is 0-based.
  446. // Get the day of week for 1/1. This can be derived from the day of week of the target day.
  447. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
  448. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
  449. // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
  450. offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
  451. if (offset != 0 && offset >= fullDays)
  452. {
  453. //
  454. // If the offset is greater than the value of fullDays, it means that
  455. // the first week of the year starts on the week where Jan/1 falls on.
  456. //
  457. offset -= 7;
  458. }
  459. //
  460. // Calculate the day of year for specified time by taking offset into account.
  461. //
  462. day = dayOfYear - offset;
  463. if (day >= 0)
  464. {
  465. //
  466. // If the day of year value is greater than zero, get the week of year.
  467. //
  468. return (day / 7 + 1);
  469. }
  470. //
  471. // Otherwise, the specified time falls on the week of previous year.
  472. // Call this method again by passing the last day of previous year.
  473. //
  474. // the last day of the previous year may "underflow" to no longer be a valid date time for
  475. // this calendar if we just subtract so we need the subclass to provide us with
  476. // that information
  477. if (time <= MinSupportedDateTime.AddDays(dayOfYear))
  478. {
  479. return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
  480. }
  481. return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
  482. }
  483. private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
  484. {
  485. int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
  486. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
  487. // Calculate the offset (how many days from the start of the year to the start of the week)
  488. int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
  489. if (offset == 0 || offset >= minimumDaysInFirstWeek)
  490. {
  491. // First of year falls in the first week of the year
  492. return 1;
  493. }
  494. int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
  495. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
  496. // starting from first day of the year, how many days do you have to go forward
  497. // before getting to the first day of the week?
  498. int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
  499. int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
  500. if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
  501. {
  502. // If the offset is greater than the minimum Days in the first week, it means that
  503. // First of year is part of the first week of the year even though it is only a partial week
  504. // add another week
  505. day += 7;
  506. }
  507. return (day / 7 + 1);
  508. }
  509. // it would be nice to make this abstract but we can't since that would break previous implementations
  510. protected virtual int DaysInYearBeforeMinSupportedYear
  511. {
  512. get
  513. {
  514. return 365;
  515. }
  516. }
  517. // Returns the week of year for the specified DateTime. The returned value is an
  518. // integer between 1 and 53.
  519. //
  520. public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
  521. {
  522. if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
  523. {
  524. throw new ArgumentOutOfRangeException(
  525. nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
  526. DayOfWeek.Sunday, DayOfWeek.Saturday));
  527. }
  528. switch (rule)
  529. {
  530. case CalendarWeekRule.FirstDay:
  531. return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
  532. case CalendarWeekRule.FirstFullWeek:
  533. return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
  534. case CalendarWeekRule.FirstFourDayWeek:
  535. return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
  536. }
  537. throw new ArgumentOutOfRangeException(
  538. nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
  539. CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
  540. }
  541. // Returns the year part of the specified DateTime. The returned value is an
  542. // integer between 1 and 9999.
  543. //
  544. public abstract int GetYear(DateTime time);
  545. // Checks whether a given day in the current era is a leap day. This method returns true if
  546. // the date is a leap day, or false if not.
  547. //
  548. public virtual bool IsLeapDay(int year, int month, int day)
  549. {
  550. return (IsLeapDay(year, month, day, CurrentEra));
  551. }
  552. // Checks whether a given day in the specified era is a leap day. This method returns true if
  553. // the date is a leap day, or false if not.
  554. //
  555. public abstract bool IsLeapDay(int year, int month, int day, int era);
  556. // Checks whether a given month in the current era is a leap month. This method returns true if
  557. // month is a leap month, or false if not.
  558. //
  559. public virtual bool IsLeapMonth(int year, int month)
  560. {
  561. return (IsLeapMonth(year, month, CurrentEra));
  562. }
  563. // Checks whether a given month in the specified era is a leap month. This method returns true if
  564. // month is a leap month, or false if not.
  565. //
  566. public abstract bool IsLeapMonth(int year, int month, int era);
  567. // Returns the leap month in a calendar year of the current era. This method returns 0
  568. // if this calendar does not have leap month, or this year is not a leap year.
  569. //
  570. public virtual int GetLeapMonth(int year)
  571. {
  572. return (GetLeapMonth(year, CurrentEra));
  573. }
  574. // Returns the leap month in a calendar year of the specified era. This method returns 0
  575. // if this calendar does not have leap month, or this year is not a leap year.
  576. //
  577. public virtual int GetLeapMonth(int year, int era)
  578. {
  579. if (!IsLeapYear(year, era))
  580. return 0;
  581. int monthsCount = GetMonthsInYear(year, era);
  582. for (int month = 1; month <= monthsCount; month++)
  583. {
  584. if (IsLeapMonth(year, month, era))
  585. return month;
  586. }
  587. return 0;
  588. }
  589. // Checks whether a given year in the current era is a leap year. This method returns true if
  590. // year is a leap year, or false if not.
  591. //
  592. public virtual bool IsLeapYear(int year)
  593. {
  594. return (IsLeapYear(year, CurrentEra));
  595. }
  596. // Checks whether a given year in the specified era is a leap year. This method returns true if
  597. // year is a leap year, or false if not.
  598. //
  599. public abstract bool IsLeapYear(int year, int era);
  600. // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
  601. //
  602. public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
  603. {
  604. return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
  605. }
  606. // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
  607. //
  608. public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
  609. internal virtual bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
  610. {
  611. result = DateTime.MinValue;
  612. try
  613. {
  614. result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
  615. return true;
  616. }
  617. catch (ArgumentException)
  618. {
  619. return false;
  620. }
  621. }
  622. internal virtual bool IsValidYear(int year, int era)
  623. {
  624. return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
  625. }
  626. internal virtual bool IsValidMonth(int year, int month, int era)
  627. {
  628. return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
  629. }
  630. internal virtual bool IsValidDay(int year, int month, int day, int era)
  631. {
  632. return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
  633. }
  634. // Returns and assigns the maximum value to represent a two digit year. This
  635. // value is the upper boundary of a 100 year range that allows a two digit year
  636. // to be properly translated to a four digit year. For example, if 2029 is the
  637. // upper boundary, then a two digit value of 30 should be interpreted as 1930
  638. // while a two digit value of 29 should be interpreted as 2029. In this example
  639. // , the 100 year range would be from 1930-2029. See ToFourDigitYear().
  640. public virtual int TwoDigitYearMax
  641. {
  642. get
  643. {
  644. return (twoDigitYearMax);
  645. }
  646. set
  647. {
  648. VerifyWritable();
  649. twoDigitYearMax = value;
  650. }
  651. }
  652. // Converts the year value to the appropriate century by using the
  653. // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
  654. // then a two digit value of 30 will get converted to 1930 while a two digit
  655. // value of 29 will get converted to 2029.
  656. public virtual int ToFourDigitYear(int year)
  657. {
  658. if (year < 0)
  659. {
  660. throw new ArgumentOutOfRangeException(nameof(year),
  661. SR.ArgumentOutOfRange_NeedNonNegNum);
  662. }
  663. if (year < 100)
  664. {
  665. return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
  666. }
  667. // If the year value is above 100, just return the year value. Don't have to do
  668. // the TwoDigitYearMax comparison.
  669. return (year);
  670. }
  671. // Return the tick count corresponding to the given hour, minute, second.
  672. // Will check the if the parameters are valid.
  673. internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
  674. {
  675. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
  676. {
  677. if (millisecond < 0 || millisecond >= MillisPerSecond)
  678. {
  679. throw new ArgumentOutOfRangeException(
  680. nameof(millisecond),
  681. string.Format(
  682. CultureInfo.InvariantCulture,
  683. SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
  684. }
  685. return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
  686. }
  687. throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
  688. }
  689. internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
  690. {
  691. int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
  692. if (twoDigitYearMax < 0)
  693. {
  694. twoDigitYearMax = defaultYearValue;
  695. }
  696. return (twoDigitYearMax);
  697. }
  698. }
  699. }