PersianCalendar.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. // Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon.
  8. // The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian)
  9. // There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day.
  10. /*
  11. ** Calendar support range:
  12. ** Calendar Minimum Maximum
  13. ** ========== ========== ==========
  14. ** Gregorian 0622/03/22 9999/12/31
  15. ** Persian 0001/01/01 9378/10/13
  16. */
  17. public class PersianCalendar : Calendar
  18. {
  19. public static readonly int PersianEra = 1;
  20. internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay;
  21. private const int ApproximateHalfYear = 180;
  22. internal const int DatePartYear = 0;
  23. internal const int DatePartDayOfYear = 1;
  24. internal const int DatePartMonth = 2;
  25. internal const int DatePartDay = 3;
  26. internal const int MonthsPerYear = 12;
  27. internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 };
  28. internal const int MaxCalendarYear = 9378;
  29. internal const int MaxCalendarMonth = 10;
  30. internal const int MaxCalendarDay = 13;
  31. // Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22)
  32. // This is the minimal Gregorian date that we support in the PersianCalendar.
  33. internal static DateTime minDate = new DateTime(622, 3, 22);
  34. internal static DateTime maxDate = DateTime.MaxValue;
  35. public override DateTime MinSupportedDateTime
  36. {
  37. get
  38. {
  39. return (minDate);
  40. }
  41. }
  42. public override DateTime MaxSupportedDateTime
  43. {
  44. get
  45. {
  46. return (maxDate);
  47. }
  48. }
  49. public override CalendarAlgorithmType AlgorithmType
  50. {
  51. get
  52. {
  53. return CalendarAlgorithmType.SolarCalendar;
  54. }
  55. }
  56. // Construct an instance of Persian calendar.
  57. public PersianCalendar()
  58. {
  59. }
  60. internal override CalendarId BaseCalendarID
  61. {
  62. get
  63. {
  64. return CalendarId.GREGORIAN;
  65. }
  66. }
  67. internal override CalendarId ID
  68. {
  69. get
  70. {
  71. return CalendarId.PERSIAN;
  72. }
  73. }
  74. /*=================================GetAbsoluteDatePersian==========================
  75. **Action: Gets the Absolute date for the given Persian date. The absolute date means
  76. ** the number of days from January 1st, 1 A.D.
  77. **Returns:
  78. **Arguments:
  79. **Exceptions:
  80. ============================================================================*/
  81. private long GetAbsoluteDatePersian(int year, int month, int day)
  82. {
  83. if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12)
  84. {
  85. int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below
  86. int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1));
  87. long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear);
  88. yearStart += ordinalDay;
  89. return yearStart;
  90. }
  91. throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
  92. }
  93. internal static void CheckTicksRange(long ticks)
  94. {
  95. if (ticks < minDate.Ticks || ticks > maxDate.Ticks)
  96. {
  97. throw new ArgumentOutOfRangeException(
  98. "time",
  99. string.Format(
  100. CultureInfo.InvariantCulture,
  101. SR.ArgumentOutOfRange_CalendarRange,
  102. minDate,
  103. maxDate));
  104. }
  105. }
  106. internal static void CheckEraRange(int era)
  107. {
  108. if (era != CurrentEra && era != PersianEra)
  109. {
  110. throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
  111. }
  112. }
  113. internal static void CheckYearRange(int year, int era)
  114. {
  115. CheckEraRange(era);
  116. if (year < 1 || year > MaxCalendarYear)
  117. {
  118. throw new ArgumentOutOfRangeException(
  119. nameof(year),
  120. string.Format(
  121. CultureInfo.CurrentCulture,
  122. SR.ArgumentOutOfRange_Range,
  123. 1,
  124. MaxCalendarYear));
  125. }
  126. }
  127. internal static void CheckYearMonthRange(int year, int month, int era)
  128. {
  129. CheckYearRange(year, era);
  130. if (year == MaxCalendarYear)
  131. {
  132. if (month > MaxCalendarMonth)
  133. {
  134. throw new ArgumentOutOfRangeException(
  135. nameof(month),
  136. string.Format(
  137. CultureInfo.CurrentCulture,
  138. SR.ArgumentOutOfRange_Range,
  139. 1,
  140. MaxCalendarMonth));
  141. }
  142. }
  143. if (month < 1 || month > 12)
  144. {
  145. throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
  146. }
  147. }
  148. private static int MonthFromOrdinalDay(int ordinalDay)
  149. {
  150. Debug.Assert(ordinalDay <= 366);
  151. int index = 0;
  152. while (ordinalDay > DaysToMonth[index])
  153. index++;
  154. return index;
  155. }
  156. private static int DaysInPreviousMonths(int month)
  157. {
  158. Debug.Assert(1 <= month && month <= 12);
  159. --month; // months are one based but for calculations use 0 based
  160. return DaysToMonth[month];
  161. }
  162. /*=================================GetDatePart==========================
  163. **Action: Returns a given date part of this <i>DateTime</i>. This method is used
  164. ** to compute the year, day-of-year, month, or day part.
  165. **Returns:
  166. **Arguments:
  167. **Exceptions: ArgumentException if part is incorrect.
  168. ============================================================================*/
  169. internal int GetDatePart(long ticks, int part)
  170. {
  171. long NumDays; // The calculation buffer in number of days.
  172. CheckTicksRange(ticks);
  173. //
  174. // Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
  175. // 1/1/0001 is absolute date 1.
  176. //
  177. NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
  178. //
  179. // Calculate the appromixate Persian Year.
  180. //
  181. long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
  182. int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
  183. Debug.Assert(y >= 1);
  184. if (part == DatePartYear)
  185. {
  186. return y;
  187. }
  188. //
  189. // Calculate the Persian Month.
  190. //
  191. int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1)));
  192. if (part == DatePartDayOfYear)
  193. {
  194. return ordinalDay;
  195. }
  196. int m = MonthFromOrdinalDay(ordinalDay);
  197. Debug.Assert(ordinalDay >= 1);
  198. Debug.Assert(m >= 1 && m <= 12);
  199. if (part == DatePartMonth)
  200. {
  201. return m;
  202. }
  203. int d = ordinalDay - DaysInPreviousMonths(m);
  204. Debug.Assert(1 <= d);
  205. Debug.Assert(d <= 31);
  206. //
  207. // Calculate the Persian Day.
  208. //
  209. if (part == DatePartDay)
  210. {
  211. return (d);
  212. }
  213. // Incorrect part value.
  214. throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
  215. }
  216. // Returns the DateTime resulting from adding the given number of
  217. // months to the specified DateTime. The result is computed by incrementing
  218. // (or decrementing) the year and month parts of the specified DateTime by
  219. // value months, and, if required, adjusting the day part of the
  220. // resulting date downwards to the last day of the resulting month in the
  221. // resulting year. The time-of-day part of the result is the same as the
  222. // time-of-day part of the specified DateTime.
  223. //
  224. // In more precise terms, considering the specified DateTime to be of the
  225. // form y / m / d + t, where y is the
  226. // year, m is the month, d is the day, and t is the
  227. // time-of-day, the result is y1 / m1 / d1 + t,
  228. // where y1 and m1 are computed by adding value months
  229. // to y and m, and d1 is the largest value less than
  230. // or equal to d that denotes a valid day in month m1 of year
  231. // y1.
  232. //
  233. public override DateTime AddMonths(DateTime time, int months)
  234. {
  235. if (months < -120000 || months > 120000)
  236. {
  237. throw new ArgumentOutOfRangeException(
  238. nameof(months),
  239. string.Format(
  240. CultureInfo.CurrentCulture,
  241. SR.ArgumentOutOfRange_Range,
  242. -120000,
  243. 120000));
  244. }
  245. // Get the date in Persian calendar.
  246. int y = GetDatePart(time.Ticks, DatePartYear);
  247. int m = GetDatePart(time.Ticks, DatePartMonth);
  248. int d = GetDatePart(time.Ticks, DatePartDay);
  249. int i = m - 1 + months;
  250. if (i >= 0)
  251. {
  252. m = i % 12 + 1;
  253. y = y + i / 12;
  254. }
  255. else
  256. {
  257. m = 12 + (i + 1) % 12;
  258. y = y + (i - 11) / 12;
  259. }
  260. int days = GetDaysInMonth(y, m);
  261. if (d > days)
  262. {
  263. d = days;
  264. }
  265. long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay;
  266. Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
  267. return (new DateTime(ticks));
  268. }
  269. // Returns the DateTime resulting from adding the given number of
  270. // years to the specified DateTime. The result is computed by incrementing
  271. // (or decrementing) the year part of the specified DateTime by value
  272. // years. If the month and day of the specified DateTime is 2/29, and if the
  273. // resulting year is not a leap year, the month and day of the resulting
  274. // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
  275. // parts of the result are the same as those of the specified DateTime.
  276. //
  277. public override DateTime AddYears(DateTime time, int years)
  278. {
  279. return (AddMonths(time, years * 12));
  280. }
  281. // Returns the day-of-month part of the specified DateTime. The returned
  282. // value is an integer between 1 and 31.
  283. //
  284. public override int GetDayOfMonth(DateTime time)
  285. {
  286. return (GetDatePart(time.Ticks, DatePartDay));
  287. }
  288. // Returns the day-of-week part of the specified DateTime. The returned value
  289. // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
  290. // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
  291. // Thursday, 5 indicates Friday, and 6 indicates Saturday.
  292. //
  293. public override DayOfWeek GetDayOfWeek(DateTime time)
  294. {
  295. return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
  296. }
  297. // Returns the day-of-year part of the specified DateTime. The returned value
  298. // is an integer between 1 and 366.
  299. //
  300. public override int GetDayOfYear(DateTime time)
  301. {
  302. return (GetDatePart(time.Ticks, DatePartDayOfYear));
  303. }
  304. // Returns the number of days in the month given by the year and
  305. // month arguments.
  306. //
  307. public override int GetDaysInMonth(int year, int month, int era)
  308. {
  309. CheckYearMonthRange(year, month, era);
  310. if ((month == MaxCalendarMonth) && (year == MaxCalendarYear))
  311. {
  312. return MaxCalendarDay;
  313. }
  314. int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
  315. if ((month == MonthsPerYear) && !IsLeapYear(year))
  316. {
  317. Debug.Assert(daysInMonth == 30);
  318. --daysInMonth;
  319. }
  320. return daysInMonth;
  321. }
  322. // Returns the number of days in the year given by the year argument for the current era.
  323. //
  324. public override int GetDaysInYear(int year, int era)
  325. {
  326. CheckYearRange(year, era);
  327. if (year == MaxCalendarYear)
  328. {
  329. return DaysToMonth[MaxCalendarMonth - 1] + MaxCalendarDay;
  330. }
  331. // Common years have 365 days. Leap years have 366 days.
  332. return (IsLeapYear(year, CurrentEra) ? 366 : 365);
  333. }
  334. // Returns the era for the specified DateTime value.
  335. public override int GetEra(DateTime time)
  336. {
  337. CheckTicksRange(time.Ticks);
  338. return (PersianEra);
  339. }
  340. public override int[] Eras
  341. {
  342. get
  343. {
  344. return (new int[] { PersianEra });
  345. }
  346. }
  347. // Returns the month part of the specified DateTime. The returned value is an
  348. // integer between 1 and 12.
  349. //
  350. public override int GetMonth(DateTime time)
  351. {
  352. return (GetDatePart(time.Ticks, DatePartMonth));
  353. }
  354. // Returns the number of months in the specified year and era.
  355. public override int GetMonthsInYear(int year, int era)
  356. {
  357. CheckYearRange(year, era);
  358. if (year == MaxCalendarYear)
  359. {
  360. return MaxCalendarMonth;
  361. }
  362. return (12);
  363. }
  364. // Returns the year part of the specified DateTime. The returned value is an
  365. // integer between 1 and MaxCalendarYear.
  366. //
  367. public override int GetYear(DateTime time)
  368. {
  369. return (GetDatePart(time.Ticks, DatePartYear));
  370. }
  371. // Checks whether a given day in the specified era is a leap day. This method returns true if
  372. // the date is a leap day, or false if not.
  373. //
  374. public override bool IsLeapDay(int year, int month, int day, int era)
  375. {
  376. // The year/month/era value checking is done in GetDaysInMonth().
  377. int daysInMonth = GetDaysInMonth(year, month, era);
  378. if (day < 1 || day > daysInMonth)
  379. {
  380. throw new ArgumentOutOfRangeException(
  381. nameof(day),
  382. string.Format(
  383. CultureInfo.CurrentCulture,
  384. SR.ArgumentOutOfRange_Day,
  385. daysInMonth,
  386. month));
  387. }
  388. return (IsLeapYear(year, era) && month == 12 && day == 30);
  389. }
  390. // Returns the leap month in a calendar year of the specified era. This method returns 0
  391. // if this calendar does not have leap month, or this year is not a leap year.
  392. //
  393. public override int GetLeapMonth(int year, int era)
  394. {
  395. CheckYearRange(year, era);
  396. return (0);
  397. }
  398. // Checks whether a given month in the specified era is a leap month. This method returns true if
  399. // month is a leap month, or false if not.
  400. //
  401. public override bool IsLeapMonth(int year, int month, int era)
  402. {
  403. CheckYearMonthRange(year, month, era);
  404. return (false);
  405. }
  406. // Checks whether a given year in the specified era is a leap year. This method returns true if
  407. // year is a leap year, or false if not.
  408. //
  409. public override bool IsLeapYear(int year, int era)
  410. {
  411. CheckYearRange(year, era);
  412. if (year == MaxCalendarYear)
  413. {
  414. return false;
  415. }
  416. return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366;
  417. }
  418. // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
  419. //
  420. public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
  421. {
  422. // The year/month/era checking is done in GetDaysInMonth().
  423. int daysInMonth = GetDaysInMonth(year, month, era);
  424. if (day < 1 || day > daysInMonth)
  425. {
  426. throw new ArgumentOutOfRangeException(
  427. nameof(day),
  428. string.Format(
  429. CultureInfo.CurrentCulture,
  430. SR.ArgumentOutOfRange_Day,
  431. daysInMonth,
  432. month));
  433. }
  434. long lDate = GetAbsoluteDatePersian(year, month, day);
  435. if (lDate >= 0)
  436. {
  437. return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
  438. }
  439. else
  440. {
  441. throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
  442. }
  443. }
  444. private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410;
  445. public override int TwoDigitYearMax
  446. {
  447. get
  448. {
  449. if (twoDigitYearMax == -1)
  450. {
  451. twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
  452. }
  453. return (twoDigitYearMax);
  454. }
  455. set
  456. {
  457. VerifyWritable();
  458. if (value < 99 || value > MaxCalendarYear)
  459. {
  460. throw new ArgumentOutOfRangeException(
  461. nameof(value),
  462. string.Format(
  463. CultureInfo.CurrentCulture,
  464. SR.ArgumentOutOfRange_Range,
  465. 99,
  466. MaxCalendarYear));
  467. }
  468. twoDigitYearMax = value;
  469. }
  470. }
  471. public override int ToFourDigitYear(int year)
  472. {
  473. if (year < 0)
  474. {
  475. throw new ArgumentOutOfRangeException(nameof(year),
  476. SR.ArgumentOutOfRange_NeedNonNegNum);
  477. }
  478. if (year < 100)
  479. {
  480. return (base.ToFourDigitYear(year));
  481. }
  482. if (year > MaxCalendarYear)
  483. {
  484. throw new ArgumentOutOfRangeException(
  485. nameof(year),
  486. string.Format(
  487. CultureInfo.CurrentCulture,
  488. SR.ArgumentOutOfRange_Range,
  489. 1,
  490. MaxCalendarYear));
  491. }
  492. return (year);
  493. }
  494. }
  495. }