More Corelib cleanup (dotnet/coreclr#26872)
[mono-project.git] / netcore / System.Private.CoreLib / shared / System / Globalization / GregorianCalendarHelper.cs
blobc1f8d96ff8ce218699a0a0b616a244fe535c1267
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.
5 namespace System.Globalization
7 // Gregorian Calendars use Era Info
8 internal class EraInfo
10 internal int era; // The value of the era.
11 internal long ticks; // The time in ticks when the era starts
12 internal int yearOffset; // The offset to Gregorian year when the era starts.
13 // Gregorian Year = Era Year + yearOffset
14 // Era Year = Gregorian Year - yearOffset
15 internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may
16 // be affected by the DateTime.MinValue;
17 internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1)
19 internal string? eraName; // The era name
20 internal string? abbrevEraName; // Abbreviated Era Name
21 internal string? englishEraName; // English era name
23 internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear)
25 this.era = era;
26 this.yearOffset = yearOffset;
27 this.minEraYear = minEraYear;
28 this.maxEraYear = maxEraYear;
29 this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
32 internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear,
33 string eraName, string abbrevEraName, string englishEraName)
35 this.era = era;
36 this.yearOffset = yearOffset;
37 this.minEraYear = minEraYear;
38 this.maxEraYear = maxEraYear;
39 this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
40 this.eraName = eraName;
41 this.abbrevEraName = abbrevEraName;
42 this.englishEraName = englishEraName;
46 // This calendar recognizes two era values:
47 // 0 CurrentEra (AD)
48 // 1 BeforeCurrentEra (BC)
49 internal class GregorianCalendarHelper
51 // 1 tick = 100ns = 10E-7 second
52 // Number of ticks per time unit
53 internal const long TicksPerMillisecond = 10000;
54 internal const long TicksPerSecond = TicksPerMillisecond * 1000;
55 internal const long TicksPerMinute = TicksPerSecond * 60;
56 internal const long TicksPerHour = TicksPerMinute * 60;
57 internal const long TicksPerDay = TicksPerHour * 24;
59 // Number of milliseconds per time unit
60 internal const int MillisPerSecond = 1000;
61 internal const int MillisPerMinute = MillisPerSecond * 60;
62 internal const int MillisPerHour = MillisPerMinute * 60;
63 internal const int MillisPerDay = MillisPerHour * 24;
65 // Number of days in a non-leap year
66 internal const int DaysPerYear = 365;
67 // Number of days in 4 years
68 internal const int DaysPer4Years = DaysPerYear * 4 + 1;
69 // Number of days in 100 years
70 internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
71 // Number of days in 400 years
72 internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
74 // Number of days from 1/1/0001 to 1/1/10000
75 internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
77 internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
79 internal const int DatePartYear = 0;
80 internal const int DatePartDayOfYear = 1;
81 internal const int DatePartMonth = 2;
82 internal const int DatePartDay = 3;
85 // This is the max Gregorian year can be represented by DateTime class. The limitation
86 // is derived from DateTime class.
88 internal int MaxYear => m_maxYear;
90 internal static readonly int[] DaysToMonth365 =
92 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
95 internal static readonly int[] DaysToMonth366 =
97 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
100 internal int m_maxYear = 9999;
101 internal int m_minYear;
102 internal Calendar m_Cal;
104 internal EraInfo[] m_EraInfo;
105 internal int[]? m_eras = null;
107 // Construct an instance of gregorian calendar.
108 internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo)
110 m_Cal = cal;
111 m_EraInfo = eraInfo;
112 m_maxYear = m_EraInfo[0].maxEraYear;
113 m_minYear = m_EraInfo[0].minEraYear;
116 // EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset
117 // Era Year = Gregorian Year - yearOffset
118 // EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue;
119 // EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1)
120 private int GetYearOffset(int year, int era, bool throwOnError)
122 if (year < 0)
124 if (throwOnError)
126 throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum);
128 return -1;
131 if (era == Calendar.CurrentEra)
133 era = m_Cal.CurrentEraValue;
136 for (int i = 0; i < m_EraInfo.Length; i++)
138 if (era == m_EraInfo[i].era)
140 if (year >= m_EraInfo[i].minEraYear)
142 if (year <= m_EraInfo[i].maxEraYear)
144 return m_EraInfo[i].yearOffset;
146 else if (!LocalAppContextSwitches.EnforceJapaneseEraYearRanges)
148 // If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before
149 // introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year
150 // can exist in one of these eras. otherwise, we'll throw.
151 // Note, we always return the offset associated with the requested era.
153 // Here is some example:
154 // if we are getting the era number 4 (Heisei) and getting the year number 32. if the era 4 has year range from 1 to 31
155 // then year 32 exceeded the range of era 4 and we'll try to find out if the years difference (32 - 31 = 1) would lay in
156 // the subsequent eras (e.g era 5 and up)
158 int remainingYears = year - m_EraInfo[i].maxEraYear;
160 for (int j = i - 1; j >= 0; j--)
162 if (remainingYears <= m_EraInfo[j].maxEraYear)
164 return m_EraInfo[i].yearOffset;
166 remainingYears -= m_EraInfo[j].maxEraYear;
171 if (throwOnError)
173 throw new ArgumentOutOfRangeException(
174 nameof(year),
175 SR.Format(
176 SR.ArgumentOutOfRange_Range,
177 m_EraInfo[i].minEraYear,
178 m_EraInfo[i].maxEraYear));
181 break; // no need to iterate more on eras.
185 if (throwOnError)
187 throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
189 return -1;
192 /*=================================GetGregorianYear==========================
193 **Action: Get the Gregorian year value for the specified year in an era.
194 **Returns: The Gregorian year value.
195 **Arguments:
196 ** year the year value in Japanese calendar
197 ** era the Japanese emperor era value.
198 **Exceptions:
199 ** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
200 ============================================================================*/
202 internal int GetGregorianYear(int year, int era)
204 return GetYearOffset(year, era, throwOnError: true) + year;
207 internal bool IsValidYear(int year, int era)
209 return GetYearOffset(year, era, throwOnError: false) >= 0;
212 // Returns a given date part of this DateTime. This method is used
213 // to compute the year, day-of-year, month, or day part.
214 internal virtual int GetDatePart(long ticks, int part)
216 CheckTicksRange(ticks);
217 // n = number of days since 1/1/0001
218 int n = (int)(ticks / TicksPerDay);
219 // y400 = number of whole 400-year periods since 1/1/0001
220 int y400 = n / DaysPer400Years;
221 // n = day number within 400-year period
222 n -= y400 * DaysPer400Years;
223 // y100 = number of whole 100-year periods within 400-year period
224 int y100 = n / DaysPer100Years;
225 // Last 100-year period has an extra day, so decrement result if 4
226 if (y100 == 4) y100 = 3;
227 // n = day number within 100-year period
228 n -= y100 * DaysPer100Years;
229 // y4 = number of whole 4-year periods within 100-year period
230 int y4 = n / DaysPer4Years;
231 // n = day number within 4-year period
232 n -= y4 * DaysPer4Years;
233 // y1 = number of whole years within 4-year period
234 int y1 = n / DaysPerYear;
235 // Last year has an extra day, so decrement result if 4
236 if (y1 == 4) y1 = 3;
237 // If year was requested, compute and return it
238 if (part == DatePartYear)
240 return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
242 // n = day number within year
243 n -= y1 * DaysPerYear;
244 // If day-of-year was requested, return it
245 if (part == DatePartDayOfYear)
247 return n + 1;
249 // Leap year calculation looks different from IsLeapYear since y1, y4,
250 // and y100 are relative to year 1, not year 0
251 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
252 int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
253 // All months have less than 32 days, so n >> 5 is a good conservative
254 // estimate for the month
255 int m = (n >> 5) + 1;
256 // m = 1-based month number
257 while (n >= days[m]) m++;
258 // If month was requested, return it
259 if (part == DatePartMonth) return m;
260 // Return 1-based day-of-month
261 return n - days[m - 1] + 1;
264 /*=================================GetAbsoluteDate==========================
265 **Action: Gets the absolute date for the given Gregorian date. The absolute date means
266 ** the number of days from January 1st, 1 A.D.
267 **Returns: the absolute date
268 **Arguments:
269 ** year the Gregorian year
270 ** month the Gregorian month
271 ** day the day
272 **Exceptions:
273 ** ArgumentOutOfRangException if year, month, day value is valid.
274 **Note:
275 ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
276 ** Number of Days in Prior Years (both common and leap years) +
277 ** Number of Days in Prior Months of Current Year +
278 ** Number of Days in Current Month
280 ============================================================================*/
282 internal static long GetAbsoluteDate(int year, int month, int day)
284 if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
286 int[] days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
287 if (day >= 1 && (day <= days[month] - days[month - 1]))
289 int y = year - 1;
290 int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
291 return absoluteDate;
294 throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
297 // Returns the tick count corresponding to the given year, month, and day.
298 // Will check the if the parameters are valid.
299 internal static long DateToTicks(int year, int month, int day)
301 return GetAbsoluteDate(year, month, day) * TicksPerDay;
304 // Return the tick count corresponding to the given hour, minute, second.
305 // Will check the if the parameters are valid.
306 internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
308 // TimeSpan.TimeToTicks is a family access function which does no error checking, so
309 // we need to put some error checking out here.
310 if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
312 if (millisecond < 0 || millisecond >= MillisPerSecond)
314 throw new ArgumentOutOfRangeException(
315 nameof(millisecond),
316 SR.Format(
317 SR.ArgumentOutOfRange_Range,
319 MillisPerSecond - 1));
321 return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
323 throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
326 internal void CheckTicksRange(long ticks)
328 if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks)
330 throw new ArgumentOutOfRangeException(
331 "time",
332 SR.Format(
333 CultureInfo.InvariantCulture,
334 SR.ArgumentOutOfRange_CalendarRange,
335 m_Cal.MinSupportedDateTime,
336 m_Cal.MaxSupportedDateTime));
340 // Returns the DateTime resulting from adding the given number of
341 // months to the specified DateTime. The result is computed by incrementing
342 // (or decrementing) the year and month parts of the specified DateTime by
343 // value months, and, if required, adjusting the day part of the
344 // resulting date downwards to the last day of the resulting month in the
345 // resulting year. The time-of-day part of the result is the same as the
346 // time-of-day part of the specified DateTime.
348 // In more precise terms, considering the specified DateTime to be of the
349 // form y / m / d + t, where y is the
350 // year, m is the month, d is the day, and t is the
351 // time-of-day, the result is y1 / m1 / d1 + t,
352 // where y1 and m1 are computed by adding value months
353 // to y and m, and d1 is the largest value less than
354 // or equal to d that denotes a valid day in month m1 of year
355 // y1.
357 public DateTime AddMonths(DateTime time, int months)
359 if (months < -120000 || months > 120000)
361 throw new ArgumentOutOfRangeException(
362 nameof(months),
363 SR.Format(
364 SR.ArgumentOutOfRange_Range,
365 -120000,
366 120000));
368 CheckTicksRange(time.Ticks);
370 int y = GetDatePart(time.Ticks, DatePartYear);
371 int m = GetDatePart(time.Ticks, DatePartMonth);
372 int d = GetDatePart(time.Ticks, DatePartDay);
373 int i = m - 1 + months;
374 if (i >= 0)
376 m = i % 12 + 1;
377 y += i / 12;
379 else
381 m = 12 + (i + 1) % 12;
382 y += (i - 11) / 12;
384 int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
385 int days = (daysArray[m] - daysArray[m - 1]);
387 if (d > days)
389 d = days;
391 long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay);
392 Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime);
393 return new DateTime(ticks);
396 // Returns the DateTime resulting from adding the given number of
397 // years to the specified DateTime. The result is computed by incrementing
398 // (or decrementing) the year part of the specified DateTime by value
399 // years. If the month and day of the specified DateTime is 2/29, and if the
400 // resulting year is not a leap year, the month and day of the resulting
401 // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
402 // parts of the result are the same as those of the specified DateTime.
404 public DateTime AddYears(DateTime time, int years)
406 return AddMonths(time, years * 12);
409 // Returns the day-of-month part of the specified DateTime. The returned
410 // value is an integer between 1 and 31.
412 public int GetDayOfMonth(DateTime time)
414 return GetDatePart(time.Ticks, DatePartDay);
417 // Returns the day-of-week part of the specified DateTime. The returned value
418 // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
419 // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
420 // Thursday, 5 indicates Friday, and 6 indicates Saturday.
422 public DayOfWeek GetDayOfWeek(DateTime time)
424 CheckTicksRange(time.Ticks);
425 return (DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7);
428 // Returns the day-of-year part of the specified DateTime. The returned value
429 // is an integer between 1 and 366.
431 public int GetDayOfYear(DateTime time)
433 return GetDatePart(time.Ticks, DatePartDayOfYear);
436 // Returns the number of days in the month given by the year and
437 // month arguments.
439 public int GetDaysInMonth(int year, int month, int era)
442 // Convert year/era value to Gregorain year value.
444 year = GetGregorianYear(year, era);
445 if (month < 1 || month > 12)
447 throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
449 int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
450 return days[month] - days[month - 1];
453 // Returns the number of days in the year given by the year argument for the current era.
456 public int GetDaysInYear(int year, int era)
459 // Convert year/era value to Gregorain year value.
461 year = GetGregorianYear(year, era);
462 return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365;
465 // Returns the era for the specified DateTime value.
466 public int GetEra(DateTime time)
468 long ticks = time.Ticks;
469 // The assumption here is that m_EraInfo is listed in reverse order.
470 for (int i = 0; i < m_EraInfo.Length; i++)
472 if (ticks >= m_EraInfo[i].ticks)
474 return m_EraInfo[i].era;
477 throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era);
480 public int[] Eras
484 if (m_eras == null)
486 m_eras = new int[m_EraInfo.Length];
487 for (int i = 0; i < m_EraInfo.Length; i++)
489 m_eras[i] = m_EraInfo[i].era;
492 return (int[])m_eras.Clone();
496 // Returns the month part of the specified DateTime. The returned value is an
497 // integer between 1 and 12.
499 public int GetMonth(DateTime time)
501 return GetDatePart(time.Ticks, DatePartMonth);
504 // Returns the number of months in the specified year and era.
505 // Always return 12.
506 public int GetMonthsInYear(int year, int era)
508 ValidateYearInEra(year, era);
509 return 12;
512 // Returns the year part of the specified DateTime. The returned value is an
513 // integer between 1 and 9999.
515 public int GetYear(DateTime time)
517 long ticks = time.Ticks;
518 int year = GetDatePart(ticks, DatePartYear);
519 for (int i = 0; i < m_EraInfo.Length; i++)
521 if (ticks >= m_EraInfo[i].ticks)
523 return year - m_EraInfo[i].yearOffset;
526 throw new ArgumentException(SR.Argument_NoEra);
529 // Returns the year that match the specified Gregorian year. The returned value is an
530 // integer between 1 and 9999.
532 public int GetYear(int year, DateTime time)
534 long ticks = time.Ticks;
535 for (int i = 0; i < m_EraInfo.Length; i++)
537 // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
538 // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
539 // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
540 // which will end up with zero as calendar year.
541 // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
542 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset)
544 return year - m_EraInfo[i].yearOffset;
547 throw new ArgumentException(SR.Argument_NoEra);
550 // Checks whether a given day in the specified era is a leap day. This method returns true if
551 // the date is a leap day, or false if not.
553 public bool IsLeapDay(int year, int month, int day, int era)
555 // year/month/era checking is done in GetDaysInMonth()
556 if (day < 1 || day > GetDaysInMonth(year, month, era))
558 throw new ArgumentOutOfRangeException(
559 nameof(day),
560 SR.Format(
561 SR.ArgumentOutOfRange_Range,
563 GetDaysInMonth(year, month, era)));
566 if (!IsLeapYear(year, era))
568 return false;
571 if (month == 2 && day == 29)
573 return true;
576 return false;
579 // Giving the calendar year and era, ValidateYearInEra will validate the existence of the input year in the input era.
580 // This method will throw if the year or the era is invalid.
581 public void ValidateYearInEra(int year, int era) => GetYearOffset(year, era, throwOnError: true);
583 // Returns the leap month in a calendar year of the specified era.
584 // This method always returns 0 as all calendars using this method don't have leap months.
585 public int GetLeapMonth(int year, int era)
587 ValidateYearInEra(year, era);
588 return 0;
591 // Checks whether a given month in the specified era is a leap month.
592 // This method always returns false as all calendars using this method don't have leap months.
593 public bool IsLeapMonth(int year, int month, int era)
595 ValidateYearInEra(year, era);
596 if (month < 1 || month > 12)
598 throw new ArgumentOutOfRangeException(
599 nameof(month),
600 SR.Format(
601 SR.ArgumentOutOfRange_Range,
603 12));
605 return false;
608 // Checks whether a given year in the specified era is a leap year. This method returns true if
609 // year is a leap year, or false if not.
611 public bool IsLeapYear(int year, int era)
613 year = GetGregorianYear(year, era);
614 return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
617 // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
619 public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
621 year = GetGregorianYear(year, era);
622 long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond);
623 CheckTicksRange(ticks);
624 return new DateTime(ticks);
627 public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
629 CheckTicksRange(time.Ticks);
630 // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear()
631 // can call GetYear() that exceeds the supported range of the Gregorian-based calendars.
632 return GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek);
635 public int ToFourDigitYear(int year, int twoDigitYearMax)
637 if (year < 0)
639 throw new ArgumentOutOfRangeException(nameof(year),
640 SR.ArgumentOutOfRange_NeedPosNum);
643 if (year < 100)
645 int y = year % 100;
646 return (twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y;
649 if (year < m_minYear || year > m_maxYear)
651 throw new ArgumentOutOfRangeException(
652 nameof(year),
653 SR.Format(SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear));
655 // If the year value is above 100, just return the year value. Don't have to do
656 // the TwoDigitYearMax comparison.
657 return year;