Calendar.cs 31 KB

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