Calendar.cs 32 KB

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