/
DateTime.cs
2074 lines (1864 loc) · 96.6 KB
/
DateTime.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
namespace System
{
// This value type represents a date and time. Every DateTime
// object has a private field (Ticks) of type Int64 that stores the
// date and time as the number of 100 nanosecond intervals since
// 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar.
//
// Starting from V2.0, DateTime also stored some context about its time
// zone in the form of a 3-state value representing Unspecified, Utc or
// Local. This is stored in the two top bits of the 64-bit numeric value
// with the remainder of the bits storing the tick count. This information
// is only used during time zone conversions and is not part of the
// identity of the DateTime. Thus, operations like Compare and Equals
// ignore this state. This is to stay compatible with earlier behavior
// and performance characteristics and to avoid forcing people into dealing
// with the effects of daylight savings. Note, that this has little effect
// on how the DateTime works except in a context where its specific time
// zone is needed, such as during conversions and some parsing and formatting
// cases.
//
// There is also 4th state stored that is a special type of Local value that
// is used to avoid data loss when round-tripping between local and UTC time.
// See below for more information on this 4th state, although it is
// effectively hidden from most users, who just see the 3-state DateTimeKind
// enumeration.
//
// For compatibility, DateTime does not serialize the Kind data when used in
// binary serialization.
//
// For a description of various calendar issues, look at
//
//
[StructLayout(LayoutKind.Auto)]
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly partial struct DateTime
: IComparable,
ISpanFormattable,
IConvertible,
IComparable<DateTime>,
IEquatable<DateTime>,
ISerializable,
ISpanParsable<DateTime>,
IUtf8SpanFormattable
{
// Number of 100ns ticks per time unit
internal const int MicrosecondsPerMillisecond = 1000;
private const long TicksPerMicrosecond = 10;
private const long TicksPerMillisecond = TicksPerMicrosecond * MicrosecondsPerMillisecond;
private const int HoursPerDay = 24;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
private const long TicksPerMinute = TicksPerSecond * 60;
private const long TicksPerHour = TicksPerMinute * 60;
private const long TicksPerDay = TicksPerHour * HoursPerDay;
// Number of milliseconds per time unit
private const int MillisPerSecond = 1000;
private const int MillisPerMinute = MillisPerSecond * 60;
private const int MillisPerHour = MillisPerMinute * 60;
private const int MillisPerDay = MillisPerHour * HoursPerDay;
// Number of days in a non-leap year
private const int DaysPerYear = 365;
// Number of days in 4 years
private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461
// Number of days in 100 years
private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524
// Number of days in 400 years
private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097
// Number of days from 1/1/0001 to 12/31/1600
private const int DaysTo1601 = DaysPer400Years * 4; // 584388
// Number of days from 1/1/0001 to 12/30/1899
private const int DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;
// Number of days from 1/1/0001 to 12/31/1969
internal const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162
// Number of days from 1/1/0001 to 12/31/9999
private const int DaysTo10000 = DaysPer400Years * 25 - 366; // 3652059
internal const long MinTicks = 0;
internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1;
private const long MaxMicroseconds = MaxTicks / TicksPerMicrosecond;
private const long MaxMillis = MaxTicks / TicksPerMillisecond;
private const long MaxSeconds = MaxTicks / TicksPerSecond;
private const long MaxMinutes = MaxTicks / TicksPerMinute;
private const long MaxHours = MaxTicks / TicksPerHour;
private const long MaxDays = (long)DaysTo10000 - 1;
internal const long UnixEpochTicks = DaysTo1970 * TicksPerDay;
private const long FileTimeOffset = DaysTo1601 * TicksPerDay;
private const long DoubleDateOffset = DaysTo1899 * TicksPerDay;
// The minimum OA date is 0100/01/01 (Note it's year 100).
// The maximum OA date is 9999/12/31
private const long OADateMinAsTicks = (DaysPer100Years - DaysPerYear) * TicksPerDay;
// All OA dates must be greater than (not >=) OADateMinAsDouble
private const double OADateMinAsDouble = -657435.0;
// All OA dates must be less than (not <=) OADateMaxAsDouble
private const double OADateMaxAsDouble = 2958466.0;
// Euclidean Affine Functions Algorithm (EAF) constants
// Constants used for fast calculation of following subexpressions
// x / DaysPer4Years
// x % DaysPer4Years / 4
private const uint EafMultiplier = (uint)(((1UL << 32) + DaysPer4Years - 1) / DaysPer4Years); // 2,939,745
private const uint EafDivider = EafMultiplier * 4; // 11,758,980
private const ulong TicksPer6Hours = TicksPerHour * 6;
private const int March1BasedDayOfNewYear = 306; // Days between March 1 and January 1
internal static ReadOnlySpan<uint> DaysToMonth365 => [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
internal static ReadOnlySpan<uint> DaysToMonth366 => [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];
private static ReadOnlySpan<byte> DaysInMonth365 => [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
private static ReadOnlySpan<byte> DaysInMonth366 => [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
public static readonly DateTime MinValue;
public static readonly DateTime MaxValue = new DateTime(MaxTicks, DateTimeKind.Unspecified);
public static readonly DateTime UnixEpoch = new DateTime(UnixEpochTicks, DateTimeKind.Utc);
private const ulong TicksMask = 0x3FFFFFFFFFFFFFFF;
private const ulong FlagsMask = 0xC000000000000000;
private const long TicksCeiling = 0x4000000000000000;
private const ulong KindUnspecified = 0x0000000000000000;
private const ulong KindUtc = 0x4000000000000000;
private const ulong KindLocal = 0x8000000000000000;
private const ulong KindLocalAmbiguousDst = 0xC000000000000000;
private const int KindShift = 62;
private const string TicksField = "ticks"; // Do not rename (binary serialization)
private const string DateDataField = "dateData"; // Do not rename (binary serialization)
// The data is stored as an unsigned 64-bit integer
// Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value
// 12/31/9999 23:59:59.9999999
// Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd
// value for the rare case where the date time is local, but is in an overlapped daylight
// savings time hour and it is in daylight savings time. This allows distinction of these
// otherwise ambiguous local times and prevents data loss when round tripping from Local to
// UTC time.
private readonly ulong _dateData;
// Constructs a DateTime from a tick count. The ticks
// argument specifies the date as the number of 100-nanosecond intervals
// that have elapsed since 1/1/0001 12:00am.
//
public DateTime(long ticks)
{
if ((ulong)ticks > MaxTicks) ThrowTicksOutOfRange();
_dateData = (ulong)ticks;
}
private DateTime(ulong dateData)
{
this._dateData = dateData;
}
internal static DateTime UnsafeCreate(long ticks) => new DateTime((ulong)ticks);
public DateTime(long ticks, DateTimeKind kind)
{
if ((ulong)ticks > MaxTicks) ThrowTicksOutOfRange();
if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind();
_dateData = (ulong)ticks | ((ulong)(uint)kind << KindShift);
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified <see cref="DateOnly"/> and <see cref="TimeOnly"/>.
/// The new instance will have the <see cref="DateTimeKind.Unspecified"/> kind.
/// </summary>
/// <param name="date">
/// The date part.
/// </param>
/// <param name="time">
/// The time part.
/// </param>
public DateTime(DateOnly date, TimeOnly time)
{
_dateData = (ulong)(date.DayNumber * TimeSpan.TicksPerDay + time.Ticks);
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified <see cref="DateOnly"/> and <see cref="TimeOnly"/> respecting a <see cref="DateTimeKind"/>.
/// </summary>
/// <param name="date">
/// The date part.
/// </param>
/// <param name="time">
/// The time part.
/// </param>
/// <param name="kind">
/// One of the enumeration values that indicates whether <paramref name="date"/>
/// and <paramref name="time"/> specify a local time, Coordinated Universal Time (UTC), or neither.
/// </param>
public DateTime(DateOnly date, TimeOnly time, DateTimeKind kind)
{
if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind();
_dateData = (ulong)(date.DayNumber * TimeSpan.TicksPerDay + time.Ticks) | ((ulong)(uint)kind << KindShift);
}
internal DateTime(long ticks, DateTimeKind kind, bool isAmbiguousDst)
{
if ((ulong)ticks > MaxTicks) ThrowTicksOutOfRange();
Debug.Assert(kind == DateTimeKind.Local, "Internal Constructor is for local times only");
_dateData = ((ulong)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal));
}
private static void ThrowTicksOutOfRange() => throw new ArgumentOutOfRangeException("ticks", SR.ArgumentOutOfRange_DateTimeBadTicks);
private static void ThrowInvalidKind() => throw new ArgumentException(SR.Argument_InvalidDateTimeKind, "kind");
private static void ThrowMillisecondOutOfRange() => throw new ArgumentOutOfRangeException("millisecond", SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1));
private static void ThrowMicrosecondOutOfRange() => throw new ArgumentOutOfRangeException("microsecond", SR.Format(SR.ArgumentOutOfRange_Range, 0, MicrosecondsPerMillisecond - 1));
private static void ThrowDateArithmetic(int param) => throw new ArgumentOutOfRangeException(param switch { 0 => "value", 1 => "t", _ => "months" }, SR.ArgumentOutOfRange_DateArithmetic);
private static void ThrowAddOutOfRange() => throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_AddValue);
// Constructs a DateTime from a given year, month, and day. The
// time-of-day of the resulting DateTime is always midnight.
//
public DateTime(int year, int month, int day)
{
_dateData = DateToTicks(year, month, day);
}
// Constructs a DateTime from a given year, month, and day for
// the specified calendar. The
// time-of-day of the resulting DateTime is always midnight.
//
public DateTime(int year, int month, int day, Calendar calendar)
: this(year, month, day, 0, 0, 0, calendar)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through the number of years in <paramref name="calendar"/>).</param>
/// <param name="month">The month (1 through the number of months in <paramref name="calendar"/>).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="calendar">The calendar that is used to interpret <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/>.</param>
/// <param name="kind">
/// One of the enumeration values that indicates whether <paramref name="year"/>, <paramref name="month"/>, <paramref name="day"/>,
/// <paramref name="hour"/>, <paramref name="minute"/>, <paramref name="second"/>, and <paramref name="millisecond"/>
/// specify a local time, Coordinated Universal Time (UTC), or neither.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="calendar"/> is <see langword="null"/>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is not in the range supported by <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than the number of months in <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="kind"/> is not one of the <see cref="DateTimeKind"/> values.
/// </exception>
/// <remarks>
/// The allowable values for <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/> parameters
/// depend on the <paramref name="calendar"/> parameter. An exception is thrown if the specified date and time cannot
/// be expressed using <paramref name="calendar"/>.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind)
{
ArgumentNullException.ThrowIfNull(calendar);
if ((uint)millisecond >= MillisPerSecond) ThrowMillisecondOutOfRange();
if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind();
if (second != 60 || !SystemSupportsLeapSeconds)
{
ulong ticks = calendar.ToDateTime(year, month, day, hour, minute, second, millisecond).UTicks;
_dateData = ticks | ((ulong)kind << KindShift);
}
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar, kind);
ValidateLeapSecond();
}
}
// Constructs a DateTime from a given year, month, day, hour,
// minute, and second.
//
public DateTime(int year, int month, int day, int hour, int minute, int second)
{
if (second != 60 || !SystemSupportsLeapSeconds)
{
_dateData = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
}
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new DateTime(year, month, day, hour, minute, 59);
ValidateLeapSecond();
}
}
public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
{
if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind();
if (second != 60 || !SystemSupportsLeapSeconds)
{
ulong ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
_dateData = ticks | ((ulong)kind << KindShift);
}
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new DateTime(year, month, day, hour, minute, 59, kind);
ValidateLeapSecond();
}
}
// Constructs a DateTime from a given year, month, day, hour,
// minute, and second for the specified calendar.
//
public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar)
{
ArgumentNullException.ThrowIfNull(calendar);
if (second != 60 || !SystemSupportsLeapSeconds)
{
_dateData = calendar.ToDateTime(year, month, day, hour, minute, second, 0).UTicks;
}
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new DateTime(year, month, day, hour, minute, 59, calendar);
ValidateLeapSecond();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than 12.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
/// </exception>
/// <remarks>
/// This constructor interprets <paramref name="year"/>, <paramref name="month"/> and <paramref name="day"/> as a year, month and day
/// in the Gregorian calendar. To instantiate a <see cref="DateTime"/> value by using the year, month and day in another calendar, call
/// the <see cref="DateTime(int, int, int, int, int, int, int, int, Calendar)"/> constructor.
///
/// The <see cref="Kind"/> property is initialized to <see cref="DateTimeKind.Unspecified"/>.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) =>
_dateData = Init(year, month, day, hour, minute, second, millisecond);
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="kind">
/// One of the enumeration values that indicates whether <paramref name="year"/>, <paramref name="month"/>, <paramref name="day"/>,
/// <paramref name="hour"/>, <paramref name="minute"/>, <paramref name="second"/>, and <paramref name="millisecond"/>
/// specify a local time, Coordinated Universal Time (UTC), or neither.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than 12.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="kind"/> is not one of the <see cref="DateTimeKind"/> values.
/// </exception>
/// <remarks>
/// This constructor interprets <paramref name="year"/>, <paramref name="month"/> and <paramref name="day"/> as a year, month and day
/// in the Gregorian calendar. To instantiate a <see cref="DateTime"/> value by using the year, month and day in another calendar, call
/// the <see cref="DateTime(int, int, int, int, int, int, int, int, Calendar, DateTimeKind)"/> constructor.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) =>
_dateData = Init(year, month, day, hour, minute, second, millisecond, kind);
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through the number of years in <paramref name="calendar"/>).</param>
/// <param name="month">The month (1 through the number of months in <paramref name="calendar"/>).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="calendar">The calendar that is used to interpret <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/>.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="calendar"/> is <see langword="null"/>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is not in the range supported by <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than the number of months in <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
/// </exception>
/// <remarks>
/// The allowable values for <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/> parameters
/// depend on the <paramref name="calendar"/> parameter. An exception is thrown if the specified date and time cannot
/// be expressed using <paramref name="calendar"/>.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar)
{
ArgumentNullException.ThrowIfNull(calendar);
if (second != 60 || !SystemSupportsLeapSeconds)
{
_dateData = calendar.ToDateTime(year, month, day, hour, minute, second, millisecond).UTicks;
}
else
{
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar);
ValidateLeapSecond();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="microsecond">The microseconds (0 through 999).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than 12.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
///
/// -or-
///
/// <paramref name="microsecond"/> is less than 0 or greater than 999.
/// </exception>
/// <remarks>
/// This constructor interprets <paramref name="year"/>, <paramref name="month"/> and <paramref name="day"/> as a year, month and day
/// in the Gregorian calendar. To instantiate a <see cref="DateTime"/> value by using the year, month and day in another calendar, call
/// the <see cref="DateTime(int, int, int, int, int, int, int, int, Calendar)"/> constructor.
///
/// The <see cref="Kind"/> property is initialized to <see cref="DateTimeKind.Unspecified"/>.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond)
: this(year, month, day, hour, minute, second, millisecond, microsecond, DateTimeKind.Unspecified)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="microsecond">The microseconds (0 through 999).</param>
/// <param name="kind">
/// One of the enumeration values that indicates whether <paramref name="year"/>, <paramref name="month"/>, <paramref name="day"/>,
/// <paramref name="hour"/>, <paramref name="minute"/>, <paramref name="second"/>, and <paramref name="millisecond"/>
/// specify a local time, Coordinated Universal Time (UTC), or neither.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than 12.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
///
/// -or-
///
/// <paramref name="microsecond"/> is less than 0 or greater than 999.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="kind"/> is not one of the <see cref="DateTimeKind"/> values.
/// </exception>
/// <remarks>
/// This constructor interprets <paramref name="year"/>, <paramref name="month"/> and <paramref name="day"/> as a year, month and day
/// in the Gregorian calendar. To instantiate a <see cref="DateTime"/> value by using the year, month and day in another calendar, call
/// the <see cref="DateTime(int, int, int, int, int, int, int, int, Calendar, DateTimeKind)"/> constructor.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, DateTimeKind kind)
{
ulong ticks = Init(year, month, day, hour, minute, second, millisecond, kind);
if ((uint)microsecond >= MicrosecondsPerMillisecond) ThrowMicrosecondOutOfRange();
ulong newTicks = (ticks & TicksMask) + (ulong)(microsecond * TicksPerMicrosecond);
Debug.Assert(newTicks <= MaxTicks);
_dateData = newTicks | (ticks & FlagsMask);
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through the number of years in <paramref name="calendar"/>).</param>
/// <param name="month">The month (1 through the number of months in <paramref name="calendar"/>).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="microsecond">The microseconds (0 through 999).</param>
/// <param name="calendar">The calendar that is used to interpret <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/>.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="calendar"/> is <see langword="null"/>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is not in the range supported by <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than the number of months in <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
///
/// -or-
///
/// <paramref name="microsecond"/> is less than 0 or greater than 999.
/// </exception>
/// <remarks>
/// The allowable values for <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/> parameters
/// depend on the <paramref name="calendar"/> parameter. An exception is thrown if the specified date and time cannot
/// be expressed using <paramref name="calendar"/>.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, Calendar calendar)
: this(year, month, day, hour, minute, second, millisecond, microsecond, calendar, DateTimeKind.Unspecified)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DateTime"/> structure to the specified year, month, day, hour, minute, second,
/// millisecond, and Coordinated Universal Time (UTC) or local time for the specified calendar.
/// </summary>
/// <param name="year">The year (1 through the number of years in <paramref name="calendar"/>).</param>
/// <param name="month">The month (1 through the number of months in <paramref name="calendar"/>).</param>
/// <param name="day">The day (1 through the number of days in <paramref name="month"/>).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="microsecond">The microseconds (0 through 999).</param>
/// <param name="calendar">The calendar that is used to interpret <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/>.</param>
/// <param name="kind">
/// One of the enumeration values that indicates whether <paramref name="year"/>, <paramref name="month"/>, <paramref name="day"/>,
/// <paramref name="hour"/>, <paramref name="minute"/>, <paramref name="second"/>, and <paramref name="millisecond"/>
/// specify a local time, Coordinated Universal Time (UTC), or neither.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="calendar"/> is <see langword="null"/>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is not in the range supported by <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="month"/> is less than 1 or greater than the number of months in <paramref name="calendar"/>.
///
/// -or-
///
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
///
/// -or-
///
/// <paramref name="hour"/> is less than 0 or greater than 23.
///
/// -or-
///
/// <paramref name="minute"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="second"/> is less than 0 or greater than 59.
///
/// -or-
///
/// <paramref name="millisecond"/> is less than 0 or greater than 999.
///
/// -or-
///
/// <paramref name="microsecond"/> is less than 0 or greater than 999.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="kind"/> is not one of the <see cref="DateTimeKind"/> values.
/// </exception>
/// <remarks>
/// The allowable values for <paramref name="year"/>, <paramref name="month"/>, and <paramref name="day"/> parameters
/// depend on the <paramref name="calendar"/> parameter. An exception is thrown if the specified date and time cannot
/// be expressed using <paramref name="calendar"/>.
///
/// For applications in which portability of date and time data or a limited degree of time zone awareness is important,
/// you can use the corresponding <see cref="DateTimeOffset"/> constructor.
/// </remarks>
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, Calendar calendar, DateTimeKind kind)
: this(year, month, day, hour, minute, second, millisecond, calendar, kind)
{
if ((uint)microsecond >= MicrosecondsPerMillisecond)
{
ThrowMicrosecondOutOfRange();
}
_dateData = new DateTime(_dateData).AddMicroseconds(microsecond)._dateData;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ulong Init(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind = DateTimeKind.Unspecified)
{
if ((uint)millisecond >= MillisPerSecond) ThrowMillisecondOutOfRange();
if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind();
if (second != 60 || !SystemSupportsLeapSeconds)
{
ulong ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
ticks += (uint)millisecond * (uint)TicksPerMillisecond;
Debug.Assert(ticks <= MaxTicks, "Input parameters validated already");
return ticks | ((ulong)kind << KindShift);
}
// if we have a leap second, then we adjust it to 59 so that DateTime will consider it the last in the specified minute.
DateTime dt = new(year, month, day, hour, minute, 59, millisecond, kind);
if (!IsValidTimeWithLeapSeconds(year, month, day, hour, 59, kind))
{
ThrowHelper.ThrowArgumentOutOfRange_BadHourMinuteSecond();
}
return dt._dateData;
}
private void ValidateLeapSecond()
{
if (!IsValidTimeWithLeapSeconds(Year, Month, Day, Hour, Minute, Kind))
{
ThrowHelper.ThrowArgumentOutOfRange_BadHourMinuteSecond();
}
}
private DateTime(SerializationInfo info, StreamingContext context)
{
if (info == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
bool foundTicks = false;
// Get the data
SerializationInfoEnumerator enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
switch (enumerator.Name)
{
case TicksField:
_dateData = (ulong)Convert.ToInt64(enumerator.Value, CultureInfo.InvariantCulture);
foundTicks = true;
continue;
case DateDataField:
_dateData = Convert.ToUInt64(enumerator.Value, CultureInfo.InvariantCulture);
goto foundData;
}
}
if (!foundTicks)
{
throw new SerializationException(SR.Serialization_MissingDateTimeData);
}
foundData:
if (UTicks > MaxTicks)
{
throw new SerializationException(SR.Serialization_DateTimeTicksOutOfRange);
}
}
private ulong UTicks => _dateData & TicksMask;
private ulong InternalKind => _dateData & FlagsMask;
// Returns the DateTime resulting from adding the given
// TimeSpan to this DateTime.
//
public DateTime Add(TimeSpan value)
{
return AddTicks(value._ticks);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private DateTime AddUnits(double value, long maxUnitCount, long ticksPerUnit)
{
if (Math.Abs(value) > maxUnitCount)
{
ThrowAddOutOfRange();
}
double integralPart = Math.Truncate(value);
double fractionalPart = value - integralPart;
long ticks = (long)(integralPart) * ticksPerUnit;
ticks += (long)(fractionalPart * ticksPerUnit);
return AddTicks(ticks);
}
/// <summary>
/// Returns a new <see cref="DateTime"/> that adds the specified number of days to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional days. The value parameter can be negative or positive.</param>
/// <returns>
/// An object whose value is the sum of the date and time represented by this instance and the number of days represented by value.
/// </returns>
public DateTime AddDays(double value) => AddUnits(value, MaxDays, TicksPerDay);
/// <summary>
/// Returns a new <see cref="DateTime"/> that adds the specified number of hours to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional hours. The value parameter can be negative or positive.</param>
/// <returns>
/// An object whose value is the sum of the date and time represented by this instance and the number of hours represented by value.
/// </returns>
public DateTime AddHours(double value) => AddUnits(value, MaxHours, TicksPerHour);
/// <summary>
/// Returns a new <see cref="DateTime"/> that adds the specified number of milliseconds to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional milliseconds. The value parameter can be negative or positive.</param>
/// <returns>
/// An object whose value is the sum of the date and time represented by this instance and the number of milliseconds represented by value.
/// </returns>
public DateTime AddMilliseconds(double value) => AddUnits(value, MaxMillis, TicksPerMillisecond);
/// <summary>
/// Returns a new <see cref="DateTime"/> that adds the specified number of microseconds to the value of this instance.
/// </summary>
/// <param name="value">
/// A number of whole and fractional microseconds.
/// The <paramref name="value"/> parameter can be negative or positive.
/// Note that this value is rounded to the nearest integer.
/// </param>
/// <returns>
/// An object whose value is the sum of the date and time represented
/// by this instance and the number of microseconds represented by <paramref name="value"/>.
/// </returns>
/// <remarks>
/// This method does not change the value of this <see cref="DateTime"/>. Instead, it returns a new <see cref="DateTime"/>
/// whose value is the result of this operation.
///
/// The fractional part of value is the fractional part of a microsecond.
/// For example, 4.5 is equivalent to 4 microseconds and 50 ticks, where one microsecond = 10 ticks.
///
/// The value parameter is rounded to the nearest integer.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// The resulting <see cref="DateTime"/> is less than <see cref="MinValue"/> or greater than <see cref="MaxValue"/>.
/// </exception>
public DateTime AddMicroseconds(double value) => AddUnits(value, MaxMicroseconds, TicksPerMicrosecond);
/// <summary>
/// Returns a new <see cref="DateTime"/> that adds the specified number of minutes to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional minutes. The value parameter can be negative or positive.</param>
/// <returns>
/// An object whose value is the sum of the date and time represented by this instance and the number of minutes represented by value.
/// </returns>
public DateTime AddMinutes(double value) => AddUnits(value, MaxMinutes, TicksPerMinute);
// Returns the DateTime resulting from adding the given number of
// months to this DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of this DateTime by
// months months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of this DateTime.
//
// In more precise terms, considering this DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding months months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public DateTime AddMonths(int months)
{
if (months < -120000 || months > 120000) throw new ArgumentOutOfRangeException(nameof(months), SR.ArgumentOutOfRange_DateTimeBadMonths);
GetDate(out int year, out int month, out int day);
int y = year, d = day;
int m = month + months;
int q = m > 0 ? (int)((uint)(m - 1) / 12) : m / 12 - 1;
y += q;
m -= q * 12;
if (y < 1 || y > 9999) ThrowDateArithmetic(2);
ReadOnlySpan<uint> daysTo = IsLeapYear(y) ? DaysToMonth366 : DaysToMonth365;
uint daysToMonth = daysTo[m - 1];
int days = (int)(daysTo[m] - daysToMonth);
if (d > days) d = days;
uint n = DaysToYear((uint)y) + daysToMonth + (uint)d - 1;
return new DateTime(n * (ulong)TicksPerDay + UTicks % TicksPerDay | InternalKind);
}
/// <summary>
/// Returns a new <see cref="DateTime"/> that adds the specified number of seconds to the value of this instance.
/// </summary>