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
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
)
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
)
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:
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;
108 // Construct an instance of gregorian calendar.
109 internal GregorianCalendarHelper(Calendar cal
, EraInfo
[] eraInfo
)
113 m_maxYear
= m_EraInfo
[0].maxEraYear
;
114 m_minYear
= m_EraInfo
[0].minEraYear
;
117 // EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset
118 // Era Year = Gregorian Year - yearOffset
119 // EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue;
120 // EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1)
121 private int GetYearOffset(int year
, int era
, bool throwOnError
)
127 throw new ArgumentOutOfRangeException(nameof(year
), SR
.ArgumentOutOfRange_NeedNonNegNum
);
132 if (era
== Calendar
.CurrentEra
)
134 era
= m_Cal
.CurrentEraValue
;
137 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
139 if (era
== m_EraInfo
[i
].era
)
141 if (year
>= m_EraInfo
[i
].minEraYear
)
143 if (year
<= m_EraInfo
[i
].maxEraYear
)
145 return m_EraInfo
[i
].yearOffset
;
147 else if (!LocalAppContextSwitches
.EnforceJapaneseEraYearRanges
)
149 // If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before
150 // introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year
151 // can exist in one of these eras. otherwise, we'll throw.
152 // Note, we always return the offset associated with the requested era.
154 // Here is some example:
155 // 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
156 // 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
157 // the subsequent eras (e.g era 5 and up)
159 int remainingYears
= year
- m_EraInfo
[i
].maxEraYear
;
161 for (int j
= i
- 1; j
>= 0; j
--)
163 if (remainingYears
<= m_EraInfo
[j
].maxEraYear
)
165 return m_EraInfo
[i
].yearOffset
;
167 remainingYears
-= m_EraInfo
[j
].maxEraYear
;
174 throw new ArgumentOutOfRangeException(
177 SR
.ArgumentOutOfRange_Range
,
178 m_EraInfo
[i
].minEraYear
,
179 m_EraInfo
[i
].maxEraYear
));
182 break; // no need to iterate more on eras.
188 throw new ArgumentOutOfRangeException(nameof(era
), SR
.ArgumentOutOfRange_InvalidEraValue
);
193 /*=================================GetGregorianYear==========================
194 **Action: Get the Gregorian year value for the specified year in an era.
195 **Returns: The Gregorian year value.
197 ** year the year value in Japanese calendar
198 ** era the Japanese emperor era value.
200 ** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
201 ============================================================================*/
203 internal int GetGregorianYear(int year
, int era
)
205 return GetYearOffset(year
, era
, throwOnError
: true) + year
;
208 internal bool IsValidYear(int year
, int era
)
210 return GetYearOffset(year
, era
, throwOnError
: false) >= 0;
213 // Returns a given date part of this DateTime. This method is used
214 // to compute the year, day-of-year, month, or day part.
215 internal virtual int GetDatePart(long ticks
, int part
)
217 CheckTicksRange(ticks
);
218 // n = number of days since 1/1/0001
219 int n
= (int)(ticks
/ TicksPerDay
);
220 // y400 = number of whole 400-year periods since 1/1/0001
221 int y400
= n
/ DaysPer400Years
;
222 // n = day number within 400-year period
223 n
-= y400
* DaysPer400Years
;
224 // y100 = number of whole 100-year periods within 400-year period
225 int y100
= n
/ DaysPer100Years
;
226 // Last 100-year period has an extra day, so decrement result if 4
227 if (y100
== 4) y100
= 3;
228 // n = day number within 100-year period
229 n
-= y100
* DaysPer100Years
;
230 // y4 = number of whole 4-year periods within 100-year period
231 int y4
= n
/ DaysPer4Years
;
232 // n = day number within 4-year period
233 n
-= y4
* DaysPer4Years
;
234 // y1 = number of whole years within 4-year period
235 int y1
= n
/ DaysPerYear
;
236 // Last year has an extra day, so decrement result if 4
238 // If year was requested, compute and return it
239 if (part
== DatePartYear
)
241 return (y400
* 400 + y100
* 100 + y4
* 4 + y1
+ 1);
243 // n = day number within year
244 n
-= y1
* DaysPerYear
;
245 // If day-of-year was requested, return it
246 if (part
== DatePartDayOfYear
)
250 // Leap year calculation looks different from IsLeapYear since y1, y4,
251 // and y100 are relative to year 1, not year 0
252 bool leapYear
= (y1
== 3 && (y4
!= 24 || y100
== 3));
253 int[] days
= leapYear
? DaysToMonth366
: DaysToMonth365
;
254 // All months have less than 32 days, so n >> 5 is a good conservative
255 // estimate for the month
256 int m
= (n
>> 5) + 1;
257 // m = 1-based month number
258 while (n
>= days
[m
]) m
++;
259 // If month was requested, return it
260 if (part
== DatePartMonth
) return (m
);
261 // Return 1-based day-of-month
262 return (n
- days
[m
- 1] + 1);
265 /*=================================GetAbsoluteDate==========================
266 **Action: Gets the absolute date for the given Gregorian date. The absolute date means
267 ** the number of days from January 1st, 1 A.D.
268 **Returns: the absolute date
270 ** year the Gregorian year
271 ** month the Gregorian month
274 ** ArgumentOutOfRangException if year, month, day value is valid.
276 ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
277 ** Number of Days in Prior Years (both common and leap years) +
278 ** Number of Days in Prior Months of Current Year +
279 ** Number of Days in Current Month
281 ============================================================================*/
283 internal static long GetAbsoluteDate(int year
, int month
, int day
)
285 if (year
>= 1 && year
<= 9999 && month
>= 1 && month
<= 12)
287 int[] days
= ((year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0))) ? DaysToMonth366
: DaysToMonth365
;
288 if (day
>= 1 && (day
<= days
[month
] - days
[month
- 1]))
291 int absoluteDate
= y
* 365 + y
/ 4 - y
/ 100 + y
/ 400 + days
[month
- 1] + day
- 1;
292 return (absoluteDate
);
295 throw new ArgumentOutOfRangeException(null, SR
.ArgumentOutOfRange_BadYearMonthDay
);
298 // Returns the tick count corresponding to the given year, month, and day.
299 // Will check the if the parameters are valid.
300 internal static long DateToTicks(int year
, int month
, int day
)
302 return (GetAbsoluteDate(year
, month
, day
) * TicksPerDay
);
305 // Return the tick count corresponding to the given hour, minute, second.
306 // Will check the if the parameters are valid.
307 internal static long TimeToTicks(int hour
, int minute
, int second
, int millisecond
)
309 // TimeSpan.TimeToTicks is a family access function which does no error checking, so
310 // we need to put some error checking out here.
311 if (hour
>= 0 && hour
< 24 && minute
>= 0 && minute
< 60 && second
>= 0 && second
< 60)
313 if (millisecond
< 0 || millisecond
>= MillisPerSecond
)
315 throw new ArgumentOutOfRangeException(
318 SR
.ArgumentOutOfRange_Range
,
320 MillisPerSecond
- 1));
322 return (InternalGlobalizationHelper
.TimeToTicks(hour
, minute
, second
) + millisecond
* TicksPerMillisecond
);
324 throw new ArgumentOutOfRangeException(null, SR
.ArgumentOutOfRange_BadHourMinuteSecond
);
328 internal void CheckTicksRange(long ticks
)
330 if (ticks
< m_Cal
.MinSupportedDateTime
.Ticks
|| ticks
> m_Cal
.MaxSupportedDateTime
.Ticks
)
332 throw new ArgumentOutOfRangeException(
335 CultureInfo
.InvariantCulture
,
336 SR
.ArgumentOutOfRange_CalendarRange
,
337 m_Cal
.MinSupportedDateTime
,
338 m_Cal
.MaxSupportedDateTime
));
342 // Returns the DateTime resulting from adding the given number of
343 // months to the specified DateTime. The result is computed by incrementing
344 // (or decrementing) the year and month parts of the specified DateTime by
345 // value months, and, if required, adjusting the day part of the
346 // resulting date downwards to the last day of the resulting month in the
347 // resulting year. The time-of-day part of the result is the same as the
348 // time-of-day part of the specified DateTime.
350 // In more precise terms, considering the specified DateTime to be of the
351 // form y / m / d + t, where y is the
352 // year, m is the month, d is the day, and t is the
353 // time-of-day, the result is y1 / m1 / d1 + t,
354 // where y1 and m1 are computed by adding value months
355 // to y and m, and d1 is the largest value less than
356 // or equal to d that denotes a valid day in month m1 of year
359 public DateTime
AddMonths(DateTime time
, int months
)
361 if (months
< -120000 || months
> 120000)
363 throw new ArgumentOutOfRangeException(
366 SR
.ArgumentOutOfRange_Range
,
370 CheckTicksRange(time
.Ticks
);
372 int y
= GetDatePart(time
.Ticks
, DatePartYear
);
373 int m
= GetDatePart(time
.Ticks
, DatePartMonth
);
374 int d
= GetDatePart(time
.Ticks
, DatePartDay
);
375 int i
= m
- 1 + months
;
383 m
= 12 + (i
+ 1) % 12;
386 int[] daysArray
= (y
% 4 == 0 && (y
% 100 != 0 || y
% 400 == 0)) ? DaysToMonth366
: DaysToMonth365
;
387 int days
= (daysArray
[m
] - daysArray
[m
- 1]);
393 long ticks
= DateToTicks(y
, m
, d
) + (time
.Ticks
% TicksPerDay
);
394 Calendar
.CheckAddResult(ticks
, m_Cal
.MinSupportedDateTime
, m_Cal
.MaxSupportedDateTime
);
395 return (new DateTime(ticks
));
398 // Returns the DateTime resulting from adding the given number of
399 // years to the specified DateTime. The result is computed by incrementing
400 // (or decrementing) the year part of the specified DateTime by value
401 // years. If the month and day of the specified DateTime is 2/29, and if the
402 // resulting year is not a leap year, the month and day of the resulting
403 // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
404 // parts of the result are the same as those of the specified DateTime.
406 public DateTime
AddYears(DateTime time
, int years
)
408 return (AddMonths(time
, years
* 12));
411 // Returns the day-of-month part of the specified DateTime. The returned
412 // value is an integer between 1 and 31.
414 public int GetDayOfMonth(DateTime time
)
416 return (GetDatePart(time
.Ticks
, DatePartDay
));
419 // Returns the day-of-week part of the specified DateTime. The returned value
420 // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
421 // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
422 // Thursday, 5 indicates Friday, and 6 indicates Saturday.
424 public DayOfWeek
GetDayOfWeek(DateTime time
)
426 CheckTicksRange(time
.Ticks
);
427 return ((DayOfWeek
)((time
.Ticks
/ TicksPerDay
+ 1) % 7));
430 // Returns the day-of-year part of the specified DateTime. The returned value
431 // is an integer between 1 and 366.
433 public int GetDayOfYear(DateTime time
)
435 return (GetDatePart(time
.Ticks
, DatePartDayOfYear
));
438 // Returns the number of days in the month given by the year and
441 public int GetDaysInMonth(int year
, int month
, int era
)
444 // Convert year/era value to Gregorain year value.
446 year
= GetGregorianYear(year
, era
);
447 if (month
< 1 || month
> 12)
449 throw new ArgumentOutOfRangeException(nameof(month
), SR
.ArgumentOutOfRange_Month
);
451 int[] days
= ((year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0)) ? DaysToMonth366
: DaysToMonth365
);
452 return (days
[month
] - days
[month
- 1]);
455 // Returns the number of days in the year given by the year argument for the current era.
458 public int GetDaysInYear(int year
, int era
)
461 // Convert year/era value to Gregorain year value.
463 year
= GetGregorianYear(year
, era
);
464 return ((year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0)) ? 366 : 365);
467 // Returns the era for the specified DateTime value.
468 public int GetEra(DateTime time
)
470 long ticks
= time
.Ticks
;
471 // The assumption here is that m_EraInfo is listed in reverse order.
472 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
474 if (ticks
>= m_EraInfo
[i
].ticks
)
476 return (m_EraInfo
[i
].era
);
479 throw new ArgumentOutOfRangeException(nameof(time
), SR
.ArgumentOutOfRange_Era
);
489 m_eras
= new int[m_EraInfo
.Length
];
490 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
492 m_eras
[i
] = m_EraInfo
[i
].era
;
495 return ((int[])m_eras
.Clone());
499 // Returns the month part of the specified DateTime. The returned value is an
500 // integer between 1 and 12.
502 public int GetMonth(DateTime time
)
504 return (GetDatePart(time
.Ticks
, DatePartMonth
));
507 // Returns the number of months in the specified year and era.
508 public int GetMonthsInYear(int year
, int era
)
510 GetGregorianYear(year
, era
);
514 // Returns the year part of the specified DateTime. The returned value is an
515 // integer between 1 and 9999.
517 public int GetYear(DateTime time
)
519 long ticks
= time
.Ticks
;
520 int year
= GetDatePart(ticks
, DatePartYear
);
521 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
523 if (ticks
>= m_EraInfo
[i
].ticks
)
525 return (year
- m_EraInfo
[i
].yearOffset
);
528 throw new ArgumentException(SR
.Argument_NoEra
);
531 // Returns the year that match the specified Gregorian year. The returned value is an
532 // integer between 1 and 9999.
534 public int GetYear(int year
, DateTime time
)
536 long ticks
= time
.Ticks
;
537 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
539 // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
540 // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
541 // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
542 // which will end up with zero as calendar year.
543 // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
544 if (ticks
>= m_EraInfo
[i
].ticks
&& year
> m_EraInfo
[i
].yearOffset
)
546 return (year
- m_EraInfo
[i
].yearOffset
);
549 throw new ArgumentException(SR
.Argument_NoEra
);
552 // Checks whether a given day in the specified era is a leap day. This method returns true if
553 // the date is a leap day, or false if not.
555 public bool IsLeapDay(int year
, int month
, int day
, int era
)
557 // year/month/era checking is done in GetDaysInMonth()
558 if (day
< 1 || day
> GetDaysInMonth(year
, month
, era
))
560 throw new ArgumentOutOfRangeException(
563 SR
.ArgumentOutOfRange_Range
,
565 GetDaysInMonth(year
, month
, era
)));
568 if (!IsLeapYear(year
, era
))
573 if (month
== 2 && day
== 29)
581 // Returns the leap month in a calendar year of the specified era. This method returns 0
582 // if this calendar does not have leap month, or this year is not a leap year.
584 public int GetLeapMonth(int year
, int era
)
586 GetGregorianYear(year
, era
);
590 // Checks whether a given month in the specified era is a leap month. This method returns true if
591 // month is a leap month, or false if not.
593 public bool IsLeapMonth(int year
, int month
, int era
)
595 year
= GetGregorianYear(year
, era
);
596 if (month
< 1 || month
> 12)
598 throw new ArgumentOutOfRangeException(
601 SR
.ArgumentOutOfRange_Range
,
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
));
636 public int ToFourDigitYear(int year
, int twoDigitYearMax
)
640 throw new ArgumentOutOfRangeException(nameof(year
),
641 SR
.ArgumentOutOfRange_NeedPosNum
);
647 return ((twoDigitYearMax
/ 100 - (y
> twoDigitYearMax
% 100 ? 1 : 0)) * 100 + y
);
650 if (year
< m_minYear
|| year
> m_maxYear
)
652 throw new ArgumentOutOfRangeException(
654 SR
.Format(SR
.ArgumentOutOfRange_Range
, m_minYear
, m_maxYear
));
656 // If the year value is above 100, just return the year value. Don't have to do
657 // the TwoDigitYearMax comparison.