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.
6 using System
.Threading
;
8 namespace System
.Globalization
10 // Gregorian Calendars use Era Info
11 internal class EraInfo
13 internal int era
; // The value of the era.
14 internal long ticks
; // The time in ticks when the era starts
15 internal int yearOffset
; // The offset to Gregorian year when the era starts.
16 // Gregorian Year = Era Year + yearOffset
17 // Era Year = Gregorian Year - yearOffset
18 internal int minEraYear
; // Min year value in this era. Generally, this value is 1, but this may
19 // be affected by the DateTime.MinValue;
20 internal int maxEraYear
; // Max year value in this era. (== the year length of the era + 1)
22 internal string? eraName
; // The era name
23 internal string? abbrevEraName
; // Abbreviated Era Name
24 internal string? englishEraName
; // English era name
26 internal EraInfo(int era
, int startYear
, int startMonth
, int startDay
, int yearOffset
, int minEraYear
, int maxEraYear
)
29 this.yearOffset
= yearOffset
;
30 this.minEraYear
= minEraYear
;
31 this.maxEraYear
= maxEraYear
;
32 this.ticks
= new DateTime(startYear
, startMonth
, startDay
).Ticks
;
35 internal EraInfo(int era
, int startYear
, int startMonth
, int startDay
, int yearOffset
, int minEraYear
, int maxEraYear
,
36 string eraName
, string abbrevEraName
, string englishEraName
)
39 this.yearOffset
= yearOffset
;
40 this.minEraYear
= minEraYear
;
41 this.maxEraYear
= maxEraYear
;
42 this.ticks
= new DateTime(startYear
, startMonth
, startDay
).Ticks
;
43 this.eraName
= eraName
;
44 this.abbrevEraName
= abbrevEraName
;
45 this.englishEraName
= englishEraName
;
49 // This calendar recognizes two era values:
51 // 1 BeforeCurrentEra (BC)
52 internal class GregorianCalendarHelper
54 // 1 tick = 100ns = 10E-7 second
55 // Number of ticks per time unit
56 internal const long TicksPerMillisecond
= 10000;
57 internal const long TicksPerSecond
= TicksPerMillisecond
* 1000;
58 internal const long TicksPerMinute
= TicksPerSecond
* 60;
59 internal const long TicksPerHour
= TicksPerMinute
* 60;
60 internal const long TicksPerDay
= TicksPerHour
* 24;
62 // Number of milliseconds per time unit
63 internal const int MillisPerSecond
= 1000;
64 internal const int MillisPerMinute
= MillisPerSecond
* 60;
65 internal const int MillisPerHour
= MillisPerMinute
* 60;
66 internal const int MillisPerDay
= MillisPerHour
* 24;
68 // Number of days in a non-leap year
69 internal const int DaysPerYear
= 365;
70 // Number of days in 4 years
71 internal const int DaysPer4Years
= DaysPerYear
* 4 + 1;
72 // Number of days in 100 years
73 internal const int DaysPer100Years
= DaysPer4Years
* 25 - 1;
74 // Number of days in 400 years
75 internal const int DaysPer400Years
= DaysPer100Years
* 4 + 1;
77 // Number of days from 1/1/0001 to 1/1/10000
78 internal const int DaysTo10000
= DaysPer400Years
* 25 - 366;
80 internal const long MaxMillis
= (long)DaysTo10000
* MillisPerDay
;
82 internal const int DatePartYear
= 0;
83 internal const int DatePartDayOfYear
= 1;
84 internal const int DatePartMonth
= 2;
85 internal const int DatePartDay
= 3;
88 // This is the max Gregorian year can be represented by DateTime class. The limitation
89 // is derived from DateTime class.
91 internal int MaxYear
=> m_maxYear
;
93 internal static readonly int[] DaysToMonth365
=
95 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
98 internal static readonly int[] DaysToMonth366
=
100 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
103 internal int m_maxYear
= 9999;
104 internal int m_minYear
;
105 internal Calendar m_Cal
;
107 internal EraInfo
[] m_EraInfo
;
108 internal int[]? m_eras
= null;
111 // Construct an instance of gregorian calendar.
112 internal GregorianCalendarHelper(Calendar cal
, EraInfo
[] eraInfo
)
116 m_maxYear
= m_EraInfo
[0].maxEraYear
;
117 m_minYear
= m_EraInfo
[0].minEraYear
; ;
120 // EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset
121 // Era Year = Gregorian Year - yearOffset
122 // EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue;
123 // EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1)
124 private int GetYearOffset(int year
, int era
, bool throwOnError
)
130 throw new ArgumentOutOfRangeException(nameof(year
), SR
.ArgumentOutOfRange_NeedNonNegNum
);
135 if (era
== Calendar
.CurrentEra
)
137 era
= m_Cal
.CurrentEraValue
;
140 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
142 if (era
== m_EraInfo
[i
].era
)
144 if (year
>= m_EraInfo
[i
].minEraYear
)
146 if (year
<= m_EraInfo
[i
].maxEraYear
)
148 return m_EraInfo
[i
].yearOffset
;
150 else if (!LocalAppContextSwitches
.EnforceJapaneseEraYearRanges
)
152 // If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before
153 // introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year
154 // can exist in one of these eras. otherwise, we'll throw.
155 // Note, we always return the offset associated with the requested era.
157 // Here is some example:
158 // 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
159 // 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
160 // the subsequent eras (e.g era 5 and up)
162 int remainingYears
= year
- m_EraInfo
[i
].maxEraYear
;
164 for (int j
= i
- 1; j
>= 0; j
--)
166 if (remainingYears
<= m_EraInfo
[j
].maxEraYear
)
168 return m_EraInfo
[i
].yearOffset
;
170 remainingYears
-= m_EraInfo
[j
].maxEraYear
;
177 throw new ArgumentOutOfRangeException(
180 SR
.ArgumentOutOfRange_Range
,
181 m_EraInfo
[i
].minEraYear
,
182 m_EraInfo
[i
].maxEraYear
));
185 break; // no need to iterate more on eras.
191 throw new ArgumentOutOfRangeException(nameof(era
), SR
.ArgumentOutOfRange_InvalidEraValue
);
196 /*=================================GetGregorianYear==========================
197 **Action: Get the Gregorian year value for the specified year in an era.
198 **Returns: The Gregorian year value.
200 ** year the year value in Japanese calendar
201 ** era the Japanese emperor era value.
203 ** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
204 ============================================================================*/
206 internal int GetGregorianYear(int year
, int era
)
208 return GetYearOffset(year
, era
, throwOnError
: true) + year
;
211 internal bool IsValidYear(int year
, int era
)
213 return GetYearOffset(year
, era
, throwOnError
: false) >= 0;
216 // Returns a given date part of this DateTime. This method is used
217 // to compute the year, day-of-year, month, or day part.
218 internal virtual int GetDatePart(long ticks
, int part
)
220 CheckTicksRange(ticks
);
221 // n = number of days since 1/1/0001
222 int n
= (int)(ticks
/ TicksPerDay
);
223 // y400 = number of whole 400-year periods since 1/1/0001
224 int y400
= n
/ DaysPer400Years
;
225 // n = day number within 400-year period
226 n
-= y400
* DaysPer400Years
;
227 // y100 = number of whole 100-year periods within 400-year period
228 int y100
= n
/ DaysPer100Years
;
229 // Last 100-year period has an extra day, so decrement result if 4
230 if (y100
== 4) y100
= 3;
231 // n = day number within 100-year period
232 n
-= y100
* DaysPer100Years
;
233 // y4 = number of whole 4-year periods within 100-year period
234 int y4
= n
/ DaysPer4Years
;
235 // n = day number within 4-year period
236 n
-= y4
* DaysPer4Years
;
237 // y1 = number of whole years within 4-year period
238 int y1
= n
/ DaysPerYear
;
239 // Last year has an extra day, so decrement result if 4
241 // If year was requested, compute and return it
242 if (part
== DatePartYear
)
244 return (y400
* 400 + y100
* 100 + y4
* 4 + y1
+ 1);
246 // n = day number within year
247 n
-= y1
* DaysPerYear
;
248 // If day-of-year was requested, return it
249 if (part
== DatePartDayOfYear
)
253 // Leap year calculation looks different from IsLeapYear since y1, y4,
254 // and y100 are relative to year 1, not year 0
255 bool leapYear
= (y1
== 3 && (y4
!= 24 || y100
== 3));
256 int[] days
= leapYear
? DaysToMonth366
: DaysToMonth365
;
257 // All months have less than 32 days, so n >> 5 is a good conservative
258 // estimate for the month
259 int m
= (n
>> 5) + 1;
260 // m = 1-based month number
261 while (n
>= days
[m
]) m
++;
262 // If month was requested, return it
263 if (part
== DatePartMonth
) return (m
);
264 // Return 1-based day-of-month
265 return (n
- days
[m
- 1] + 1);
268 /*=================================GetAbsoluteDate==========================
269 **Action: Gets the absolute date for the given Gregorian date. The absolute date means
270 ** the number of days from January 1st, 1 A.D.
271 **Returns: the absolute date
273 ** year the Gregorian year
274 ** month the Gregorian month
277 ** ArgumentOutOfRangException if year, month, day value is valid.
279 ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
280 ** Number of Days in Prior Years (both common and leap years) +
281 ** Number of Days in Prior Months of Current Year +
282 ** Number of Days in Current Month
284 ============================================================================*/
286 internal static long GetAbsoluteDate(int year
, int month
, int day
)
288 if (year
>= 1 && year
<= 9999 && month
>= 1 && month
<= 12)
290 int[] days
= ((year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0))) ? DaysToMonth366
: DaysToMonth365
;
291 if (day
>= 1 && (day
<= days
[month
] - days
[month
- 1]))
294 int absoluteDate
= y
* 365 + y
/ 4 - y
/ 100 + y
/ 400 + days
[month
- 1] + day
- 1;
295 return (absoluteDate
);
298 throw new ArgumentOutOfRangeException(null, SR
.ArgumentOutOfRange_BadYearMonthDay
);
301 // Returns the tick count corresponding to the given year, month, and day.
302 // Will check the if the parameters are valid.
303 internal static long DateToTicks(int year
, int month
, int day
)
305 return (GetAbsoluteDate(year
, month
, day
) * TicksPerDay
);
308 // Return the tick count corresponding to the given hour, minute, second.
309 // Will check the if the parameters are valid.
310 internal static long TimeToTicks(int hour
, int minute
, int second
, int millisecond
)
312 //TimeSpan.TimeToTicks is a family access function which does no error checking, so
313 //we need to put some error checking out here.
314 if (hour
>= 0 && hour
< 24 && minute
>= 0 && minute
< 60 && second
>= 0 && second
< 60)
316 if (millisecond
< 0 || millisecond
>= MillisPerSecond
)
318 throw new ArgumentOutOfRangeException(
321 SR
.ArgumentOutOfRange_Range
,
323 MillisPerSecond
- 1));
325 return (InternalGlobalizationHelper
.TimeToTicks(hour
, minute
, second
) + millisecond
* TicksPerMillisecond
); ;
327 throw new ArgumentOutOfRangeException(null, SR
.ArgumentOutOfRange_BadHourMinuteSecond
);
331 internal void CheckTicksRange(long ticks
)
333 if (ticks
< m_Cal
.MinSupportedDateTime
.Ticks
|| ticks
> m_Cal
.MaxSupportedDateTime
.Ticks
)
335 throw new ArgumentOutOfRangeException(
338 CultureInfo
.InvariantCulture
,
339 SR
.ArgumentOutOfRange_CalendarRange
,
340 m_Cal
.MinSupportedDateTime
,
341 m_Cal
.MaxSupportedDateTime
));
345 // Returns the DateTime resulting from adding the given number of
346 // months to the specified DateTime. The result is computed by incrementing
347 // (or decrementing) the year and month parts of the specified DateTime by
348 // value months, and, if required, adjusting the day part of the
349 // resulting date downwards to the last day of the resulting month in the
350 // resulting year. The time-of-day part of the result is the same as the
351 // time-of-day part of the specified DateTime.
353 // In more precise terms, considering the specified DateTime to be of the
354 // form y / m / d + t, where y is the
355 // year, m is the month, d is the day, and t is the
356 // time-of-day, the result is y1 / m1 / d1 + t,
357 // where y1 and m1 are computed by adding value months
358 // to y and m, and d1 is the largest value less than
359 // or equal to d that denotes a valid day in month m1 of year
362 public DateTime
AddMonths(DateTime time
, int months
)
364 if (months
< -120000 || months
> 120000)
366 throw new ArgumentOutOfRangeException(
369 SR
.ArgumentOutOfRange_Range
,
373 CheckTicksRange(time
.Ticks
);
375 int y
= GetDatePart(time
.Ticks
, DatePartYear
);
376 int m
= GetDatePart(time
.Ticks
, DatePartMonth
);
377 int d
= GetDatePart(time
.Ticks
, DatePartDay
);
378 int i
= m
- 1 + months
;
386 m
= 12 + (i
+ 1) % 12;
389 int[] daysArray
= (y
% 4 == 0 && (y
% 100 != 0 || y
% 400 == 0)) ? DaysToMonth366
: DaysToMonth365
;
390 int days
= (daysArray
[m
] - daysArray
[m
- 1]);
396 long ticks
= DateToTicks(y
, m
, d
) + (time
.Ticks
% TicksPerDay
);
397 Calendar
.CheckAddResult(ticks
, m_Cal
.MinSupportedDateTime
, m_Cal
.MaxSupportedDateTime
);
398 return (new DateTime(ticks
));
401 // Returns the DateTime resulting from adding the given number of
402 // years to the specified DateTime. The result is computed by incrementing
403 // (or decrementing) the year part of the specified DateTime by value
404 // years. If the month and day of the specified DateTime is 2/29, and if the
405 // resulting year is not a leap year, the month and day of the resulting
406 // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
407 // parts of the result are the same as those of the specified DateTime.
409 public DateTime
AddYears(DateTime time
, int years
)
411 return (AddMonths(time
, years
* 12));
414 // Returns the day-of-month part of the specified DateTime. The returned
415 // value is an integer between 1 and 31.
417 public int GetDayOfMonth(DateTime time
)
419 return (GetDatePart(time
.Ticks
, DatePartDay
));
422 // Returns the day-of-week part of the specified DateTime. The returned value
423 // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
424 // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
425 // Thursday, 5 indicates Friday, and 6 indicates Saturday.
427 public DayOfWeek
GetDayOfWeek(DateTime time
)
429 CheckTicksRange(time
.Ticks
);
430 return ((DayOfWeek
)((time
.Ticks
/ TicksPerDay
+ 1) % 7));
433 // Returns the day-of-year part of the specified DateTime. The returned value
434 // is an integer between 1 and 366.
436 public int GetDayOfYear(DateTime time
)
438 return (GetDatePart(time
.Ticks
, DatePartDayOfYear
));
441 // Returns the number of days in the month given by the year and
444 public int GetDaysInMonth(int year
, int month
, int era
)
447 // Convert year/era value to Gregorain year value.
449 year
= GetGregorianYear(year
, era
);
450 if (month
< 1 || month
> 12)
452 throw new ArgumentOutOfRangeException(nameof(month
), SR
.ArgumentOutOfRange_Month
);
454 int[] days
= ((year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0)) ? DaysToMonth366
: DaysToMonth365
);
455 return (days
[month
] - days
[month
- 1]);
458 // Returns the number of days in the year given by the year argument for the current era.
461 public int GetDaysInYear(int year
, int era
)
464 // Convert year/era value to Gregorain year value.
466 year
= GetGregorianYear(year
, era
);
467 return ((year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0)) ? 366 : 365);
470 // Returns the era for the specified DateTime value.
471 public int GetEra(DateTime time
)
473 long ticks
= time
.Ticks
;
474 // The assumption here is that m_EraInfo is listed in reverse order.
475 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
477 if (ticks
>= m_EraInfo
[i
].ticks
)
479 return (m_EraInfo
[i
].era
);
482 throw new ArgumentOutOfRangeException(nameof(time
), SR
.ArgumentOutOfRange_Era
);
492 m_eras
= new int[m_EraInfo
.Length
];
493 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
495 m_eras
[i
] = m_EraInfo
[i
].era
;
498 return ((int[])m_eras
.Clone());
502 // Returns the month part of the specified DateTime. The returned value is an
503 // integer between 1 and 12.
505 public int GetMonth(DateTime time
)
507 return (GetDatePart(time
.Ticks
, DatePartMonth
));
510 // Returns the number of months in the specified year and era.
511 public int GetMonthsInYear(int year
, int era
)
513 GetGregorianYear(year
, era
);
517 // Returns the year part of the specified DateTime. The returned value is an
518 // integer between 1 and 9999.
520 public int GetYear(DateTime time
)
522 long ticks
= time
.Ticks
;
523 int year
= GetDatePart(ticks
, DatePartYear
);
524 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
526 if (ticks
>= m_EraInfo
[i
].ticks
)
528 return (year
- m_EraInfo
[i
].yearOffset
);
531 throw new ArgumentException(SR
.Argument_NoEra
);
534 // Returns the year that match the specified Gregorian year. The returned value is an
535 // integer between 1 and 9999.
537 public int GetYear(int year
, DateTime time
)
539 long ticks
= time
.Ticks
;
540 for (int i
= 0; i
< m_EraInfo
.Length
; i
++)
542 // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
543 // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
544 // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
545 // which will end up with zero as calendar year.
546 // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
547 if (ticks
>= m_EraInfo
[i
].ticks
&& year
> m_EraInfo
[i
].yearOffset
)
549 return (year
- m_EraInfo
[i
].yearOffset
);
552 throw new ArgumentException(SR
.Argument_NoEra
);
555 // Checks whether a given day in the specified era is a leap day. This method returns true if
556 // the date is a leap day, or false if not.
558 public bool IsLeapDay(int year
, int month
, int day
, int era
)
560 // year/month/era checking is done in GetDaysInMonth()
561 if (day
< 1 || day
> GetDaysInMonth(year
, month
, era
))
563 throw new ArgumentOutOfRangeException(
566 SR
.ArgumentOutOfRange_Range
,
568 GetDaysInMonth(year
, month
, era
)));
571 if (!IsLeapYear(year
, era
))
576 if (month
== 2 && day
== 29)
584 // Returns the leap month in a calendar year of the specified era. This method returns 0
585 // if this calendar does not have leap month, or this year is not a leap year.
587 public int GetLeapMonth(int year
, int era
)
589 GetGregorianYear(year
, era
);
593 // Checks whether a given month in the specified era is a leap month. This method returns true if
594 // month is a leap month, or false if not.
596 public bool IsLeapMonth(int year
, int month
, int era
)
598 year
= GetGregorianYear(year
, era
);
599 if (month
< 1 || month
> 12)
601 throw new ArgumentOutOfRangeException(
604 SR
.ArgumentOutOfRange_Range
,
611 // Checks whether a given year in the specified era is a leap year. This method returns true if
612 // year is a leap year, or false if not.
614 public bool IsLeapYear(int year
, int era
)
616 year
= GetGregorianYear(year
, era
);
617 return (year
% 4 == 0 && (year
% 100 != 0 || year
% 400 == 0));
620 // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
622 public DateTime
ToDateTime(int year
, int month
, int day
, int hour
, int minute
, int second
, int millisecond
, int era
)
624 year
= GetGregorianYear(year
, era
);
625 long ticks
= DateToTicks(year
, month
, day
) + TimeToTicks(hour
, minute
, second
, millisecond
);
626 CheckTicksRange(ticks
);
627 return (new DateTime(ticks
));
630 public virtual int GetWeekOfYear(DateTime time
, CalendarWeekRule rule
, DayOfWeek firstDayOfWeek
)
632 CheckTicksRange(time
.Ticks
);
633 // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear()
634 // can call GetYear() that exceeds the supported range of the Gregorian-based calendars.
635 return (GregorianCalendar
.GetDefaultInstance().GetWeekOfYear(time
, rule
, firstDayOfWeek
));
639 public int ToFourDigitYear(int year
, int twoDigitYearMax
)
643 throw new ArgumentOutOfRangeException(nameof(year
),
644 SR
.ArgumentOutOfRange_NeedPosNum
);
650 return ((twoDigitYearMax
/ 100 - (y
> twoDigitYearMax
% 100 ? 1 : 0)) * 100 + y
);
653 if (year
< m_minYear
|| year
> m_maxYear
)
655 throw new ArgumentOutOfRangeException(
657 SR
.Format(SR
.ArgumentOutOfRange_Range
, m_minYear
, m_maxYear
));
659 // If the year value is above 100, just return the year value. Don't have to do
660 // the TwoDigitYearMax comparison.