This repository was archived by the owner on Aug 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 339
Expand file tree
/
Copy pathDate.cs
More file actions
1842 lines (1664 loc) · 83.6 KB
/
Date.cs
File metadata and controls
1842 lines (1664 loc) · 83.6 KB
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.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System
{
/// <summary>
/// Represents a whole date, having a year, month and day component.
/// All values are in the proleptic Gregorian (ISO 8601) calendar system unless otherwise specified.
/// </summary>
[Serializable]
[XmlSchemaProvider("GetSchema")]
[StructLayout(LayoutKind.Auto)]
public struct Date : IEquatable<Date>, IComparable<Date>, IComparable, IFormattable, IXmlSerializable
{
private const int MinDayNumber = 0;
private const int MaxDayNumber = 3652058;
private static readonly Regex EscapeCharRegex = new Regex(@"\\.|"".*?""|'.*?'", RegexOptions.Compiled);
private static readonly Regex InvalidFormatsRegex = new Regex(@"[fFghHKmstz:]+|%[fFgGrRtTuU]", RegexOptions.Compiled);
private static readonly Regex ISOFormatRegex = new Regex(@"%[Oos]", RegexOptions.Compiled);
/// <summary>
/// Represents the smallest possible value of <see cref="Date"/>. This field is read-only.
/// </summary>
public static readonly Date MinValue = new Date(MinDayNumber);
/// <summary>
/// Represents the largest possible value of <see cref="Date"/>. This field is read-only.
/// </summary>
public static readonly Date MaxValue = new Date(MaxDayNumber);
// 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
// The following arrays contain the starting day-of-year number of each month, for regular and leap years
private static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
private static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
// internal enum
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of whole days since 0001-01-01 (which is day 0)
// NOTE: This is the only field in this structure.
private readonly int _dayNumber;
/// <summary>
/// Initializes a new instance of a <see cref="Date"/> structure to a specified number of days.
/// </summary>
/// <param name="dayNumber">The number of days since January 1, 0001 in the proleptic Gregorian calendar.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="dayNumber"/> is out of the range supported by the <see cref="Date"/> object.
/// </exception>
public Date(int dayNumber)
{
if (dayNumber < MinDayNumber || dayNumber > MaxDayNumber)
{
throw new ArgumentOutOfRangeException(nameof(dayNumber), dayNumber, Strings.ArgumentOutOfRange_BadDayNumber);
}
Contract.EndContractBlock();
_dayNumber = dayNumber;
}
/// <summary>
/// Initializes a new instance of a <see cref="Date"/> structure to a specified year, month, and day.
/// </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>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
/// <para>-or-</para>
/// <paramref name="month"/> is less than 1 or greater than 12.
/// <para>-or-</para>
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
/// </exception>
public Date(int year, int month, int day)
{
_dayNumber = DateToDayNumber(year, month, day);
}
/// <summary>
/// Initializes a new instance of Date structure to a specified year, month, and day 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="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 null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is not in the range supported by <paramref name="calendar"/>.
/// <para>-or-</para>
/// <paramref name="month"/> is less than 1 or greater than the number of months in <paramref name="calendar"/>.
/// <para>-or-</para>
/// <paramref name="day"/> is less than 1 or greater than the number of days in <paramref name="month"/>.
/// </exception>
public Date(int year, int month, int day, Calendar calendar)
{
if (calendar == null)
{
throw new ArgumentNullException(nameof(calendar));
}
DateTime dt = calendar.ToDateTime(year, month, day, 0, 0, 0, 0);
_dayNumber = (int)(dt.Ticks / TimeSpan.TicksPerDay);
}
/// <summary>
/// Initializes a new instance of a <see cref="Date"/> structure to a specified year, and day of year.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="dayOfYear">The day of year (1 through the number of days in <paramref name="year"/>).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
/// <para>-or-</para>
/// <paramref name="dayOfYear"/> is less than 1 or greater than the number of days in <paramref name="year"/>.
/// </exception>
/// <remarks>
/// Note that standard years have days numbered 1 through 365, while leap years have days numbered 1 through 366.
/// </remarks>
public Date(int year, int dayOfYear)
{
if (dayOfYear < 1 || dayOfYear > (IsLeapYear(year) ? 366 : 365))
{
throw new ArgumentOutOfRangeException(nameof(dayOfYear), dayOfYear, Strings.ArgumentOutOfRange_BadYearDay);
}
Contract.EndContractBlock();
_dayNumber = DateToDayNumber(year, 1, 1) + dayOfYear - 1;
}
/// <summary>
/// Gets the year component of the date represented by this instance.
/// </summary>
/// <value>The year component, expressed as a value between 1 and 9999.</value>
public int Year
{
get
{
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 9999);
return GetDatePart(DatePartYear);
}
}
/// <summary>
/// Gets the month component of the date represented by this instance.
/// </summary>
/// <value>The month component, expressed as a value between 1 and 12.</value>
public int Month
{
get
{
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 12);
return GetDatePart(DatePartMonth);
}
}
/// <summary>
/// Gets the day component of the date represented by this instance.
/// </summary>
/// <value>The day component, expressed as a value between 1 and 31.</value>
public int Day
{
get
{
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 31);
return GetDatePart(DatePartDay);
}
}
/// <summary>
/// Gets the day of the year represented by this instance.
/// </summary>
/// <value>The day of the year, expressed as a value between 1 and 366.</value>
public int DayOfYear
{
get
{
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 366);
return GetDatePart(DatePartDayOfYear);
}
}
/// <summary>
/// Gets the day of the week represented by this instance.
/// </summary>
/// <value>An enumerated constant that indicates the day of the week of this <see cref="Date"/> value.</value>
public DayOfWeek DayOfWeek
{
get
{
Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
return (DayOfWeek)((_dayNumber + 1) % 7);
}
}
/// <summary>
/// Gets the number of days since January 1, 0001 in the proleptic Gregorian calendar.
/// </summary>
/// <value>
/// The number of days that represent the date of this instance.
/// The value is between <c>Date.MinValue.DayNumber</c> and <c>Date.MaxValue.DayNumber</c>.
/// </value>
public int DayNumber
{
get
{
Contract.Ensures(Contract.Result<int>() >= MinDayNumber);
Contract.Ensures(Contract.Result<int>() <= MaxDayNumber);
return _dayNumber;
}
}
/// <summary>
/// Creates a <see cref="DateTime"/> object from the current <see cref="Date"/> and the specified <see cref="Time"/>.
/// The resulting value has a <see cref="DateTime.Kind"/> of <see cref="DateTimeKind.Unspecified"/>.
/// </summary>
/// <remarks>
/// Since neither <see cref="Date"/> or <see cref="Time"/> keep track of <see cref="DateTimeKind"/>,
/// recognize that the <see cref="DateTime"/> produced by <c>Date.Today.At(Time.Now)</c> will have
/// <see cref="DateTimeKind.Unspecified"/>, rather than then <see cref="DateTimeKind.Local"/> that would be
/// given by <c>DateTime.Now</c>.
/// <para>The same applies for <see cref="DateTimeKind.Utc"/>.</para>
/// </remarks>
public DateTime At(Time time)
{
long ticks = _dayNumber * TimeSpan.TicksPerDay + time.Ticks;
return new DateTime(ticks);
}
/// <summary>
/// Creates a <see cref="DateTime"/> object from the current <see cref="Date"/>, with the time set to midnight
/// (00:00:00). The resulting value has a <see cref="DateTime.Kind"/> of <see cref="DateTimeKind.Unspecified"/>.
/// </summary>
/// <remarks>
/// Note that midnight might be ambiguous or invalid in some time zones on DST transition days.
/// Though this method is time zone ignorant, the resulting value should be considered suspect and used with
/// caution.
/// </remarks>
public DateTime ToDateTimeAtMidnight()
{
return new DateTime(_dayNumber * TimeSpan.TicksPerDay);
}
/// <summary>
/// Returns an indication whether the specified year is a leap year.
/// </summary>
/// <param name="year">A 4-digit year.</param>
/// <returns><c>true</c> if year is a leap year; otherwise, <c>false</c>.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="year"/> is less than 1 or greater than 9999.
/// </exception>
public static bool IsLeapYear(int year)
{
if (year < 1 || year > 9999)
{
throw new ArgumentOutOfRangeException(nameof(year), year, Strings.ArgumentOutOfRange_Year);
}
Contract.EndContractBlock();
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
/// <summary>
/// Returns the number of days in the specified month and year.
/// </summary>
/// <returns>
/// The number of days in <paramref name="month"/> for the specified <paramref name="year"/>.
/// For example, if <paramref name="month"/> equals 2 for February, the return value is 28 or 29 depending
/// upon whether <paramref name="year"/> is a leap year.
/// </returns>
/// <param name="year">The year.</param>
/// <param name="month">The month (a number ranging from 1 to 12).</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="month"/> is less than 1 or greater than 12.
/// <para>-or-</para>
/// <paramref name="year"/> is less than 1 or greater than 9999.
/// </exception>
public static int DaysInMonth(int year, int month)
{
if (year < 1 || year > 9999)
{
throw new ArgumentOutOfRangeException(nameof(year), year, Strings.ArgumentOutOfRange_Year);
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), month, Strings.ArgumentOutOfRange_Month);
}
Contract.EndContractBlock();
// IsLeapYear checks the year argument
int[] days = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
return days[month] - days[month - 1];
}
/// <summary>
/// Gets a <see cref="Date"/> object that is set to the current date in the specified time zone.
/// </summary>
/// <param name="timeZoneInfo">The <see cref="TimeZoneInfo"/> instance.</param>
/// <returns>The current <see cref="Date"/> for the specified time zone.</returns>
public static Date TodayInTimeZone(TimeZoneInfo timeZoneInfo)
{
DateTimeOffset utcNow = DateTimeOffset.UtcNow;
DateTimeOffset localNow = TimeZoneInfo.ConvertTime(utcNow, timeZoneInfo);
return DateFromDateTime(localNow.Date);
}
/// <summary>
/// Gets a <see cref="Date"/> object that is set to the current date,
/// expressed in this computer's local time zone.
/// </summary>
/// <value>An object whose value is the current local date.</value>
public static Date Today
{
get
{
DateTime localNow = DateTime.Now;
return DateFromDateTime(localNow);
}
}
/// <summary>
/// Gets a <see cref="Date"/> object that is set to the current date,
/// expressed as Coordinated Universal Time (UTC).
/// </summary>
/// <value>An object whose value is the current UTC date.</value>
public static Date UtcToday
{
get
{
DateTime utcNow = DateTime.UtcNow;
return DateFromDateTime(utcNow);
}
}
/// <summary>
/// Gets a <see cref="Date"/> object whose value is ahead or behind the value of this instance by the specified
/// number of years. Positive values will move the date forward; negative values will move the date backwards.
/// <para>
/// If the original date is a leap day (February 29), and the resulting year is not a leap year, the resulting
/// value will be adjusted to February 28.
/// </para>
/// </summary>
/// <param name="years">The number of years to adjust by. The value can be negative or positive.</param>
/// <returns>
/// A new <see cref="Date"/> object which is the result of adjusting this instance by the
/// <paramref name="years"/> specified.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="years"/> or the resulting <see cref="Date"/> is less than <see cref="Date.MinValue"/>
/// or greater than <see cref="Date.MaxValue"/>.
/// </exception>
public Date AddYears(int years)
{
if (years <= -10000 || years >= 10000)
{
throw new ArgumentOutOfRangeException(nameof(years), years, Strings.ArgumentOutOfRange_BadYears);
}
Contract.EndContractBlock();
return AddMonths(years * 12);
}
/// <summary>
/// Gets a <see cref="Date"/> object whose value is ahead or behind the value of this instance by the specified
/// number of months. Positive values will move the date forward; negative values will move the date backwards.
/// <para>
/// Since the number of days in a months varies, the resulting date may not necessarily fall on the same
/// day. If the resulting value would have landed on a day that doesn't exist within a month, the value is
/// adjusted backward to the last day of the month.
/// </para>
/// </summary>
/// <param name="months">The number of months to adjust by. The value can be negative or positive.</param>
/// <returns>
/// A new <see cref="Date"/> object which is the result of adjusting this instance by the
/// <paramref name="months"/> specified.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="months"/> or the resulting <see cref="Date"/> is less than <see cref="Date.MinValue"/>
/// or greater than <see cref="Date.MaxValue"/>.
/// </exception>
public Date AddMonths(int months)
{
if (months <= -120000 || months >= 120000)
{
throw new ArgumentOutOfRangeException(nameof(months), months, Strings.ArgumentOutOfRange_BadMonths);
}
Contract.EndContractBlock();
GetDatePart(out int y, out int m, out int d);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
if (y < 1 || y > 9999)
{
throw new ArgumentOutOfRangeException(nameof(months), months, Strings.ArgumentOutOfRange_DateArithmetic);
}
int days = DaysInMonth(y, m);
if (d > days)
{
d = days;
}
var dayNumber = DateToDayNumber(y, m, d);
return new Date(dayNumber);
}
/// <summary>
/// Gets a <see cref="Date"/> object whose value is ahead or behind the value of this instance by the specified
/// number of days. Positive values will move the date forward; negative values will move the date backwards.
/// </summary>
/// <param name="days">The number of days to adjust by. The value can be negative or positive.</param>
/// <returns>
/// A new <see cref="Date"/> object which is the result of adjusting this instance by the
/// <paramref name="days"/> specified.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="days"/> or the resulting <see cref="Date"/> is less than <see cref="Date.MinValue"/>
/// or greater than <see cref="Date.MaxValue"/>.
/// </exception>
public Date AddDays(int days)
{
int dayNumber = _dayNumber + days;
if (dayNumber < MinDayNumber || dayNumber > MaxDayNumber)
{
throw new ArgumentOutOfRangeException(nameof(days), days, Strings.ArgumentOutOfRange_DateArithmetic);
}
Contract.EndContractBlock();
return new Date(dayNumber);
}
/// <summary>
/// Returns the number of days remaining from this date to the <paramref name="date"/> specified.
/// If the <paramref name="date"/> has already passed, the result will be negative.
/// </summary>
/// <param name="date">The target <see cref="Date"/> value.</param>
/// <returns>The integer number of days until the date specified.</returns>
/// <remarks>
/// This operation uses an exclusive upper bound.
/// For example, if the current instance represents January 1st, there is one day until January 2nd.
/// </remarks>
public int DaysUntil(Date date)
{
return date.DayNumber - _dayNumber;
}
/// <summary>
/// Returns the number of days elapsed from the <paramref name="date"/> specified to this date.
/// If the <paramref name="date"/> has not yet passed, the result will be negative.
/// </summary>
/// <param name="date">The target <see cref="Date"/> value.</param>
/// <returns>The integer number of days since the date specified.</returns>
/// <remarks>
/// This operation uses an exclusive upper bound.
/// For example, if the current instance represents January 2nd, there has been one day since January 1st.
/// </remarks>
public int DaysSince(Date date)
{
return _dayNumber - date.DayNumber;
}
/// <summary>
/// Returns the number of whole months remaining from this date to the <paramref name="date"/> specified.
/// If the <paramref name="date"/> has already passed, the result will be negative.
/// </summary>
/// <param name="date">The target <see cref="Date"/> value.</param>
/// <returns>The integer number of whole months until the date specified.</returns>
/// <remarks>
/// This operation uses an exclusive upper bound.
/// For example, if the current instance represents January 1st, there is one month until February 1st.
/// </remarks>
public int MonthsUntil(Date date)
{
if (this == date)
{
return 0;
}
int months = (date.Year * 12 + date.Month) - (this.Year * 12 + this.Month);
var d = date.AddMonths(-months);
if (date > this)
{
if (this > d)
{
months--;
}
}
else
{
if (this < d)
{
months++;
}
}
return months;
}
/// <summary>
/// Returns the number of whole months elapsed from the <paramref name="date"/> specified to this date.
/// If the <paramref name="date"/> has not yet passed, the result will be negative.
/// </summary>
/// <param name="date">The target <see cref="Date"/> value.</param>
/// <returns>The integer number of whole months since the date specified.</returns>
/// <remarks>
/// This operation uses an exclusive upper bound.
/// For example, if the current instance represents February 1st, there has been one month since January 1st.
/// </remarks>
public int MonthsSince(Date date)
{
return date.MonthsUntil(this);
}
/// <summary>
/// Returns the number of whole years remaining from this date to the <paramref name="date"/> specified.
/// If the <paramref name="date"/> has already passed, the result will be negative.
/// </summary>
/// <param name="date">The target <see cref="Date"/> value.</param>
/// <returns>The integer number of whole years until the date specified.</returns>
/// <remarks>
/// This operation uses an exclusive upper bound.
/// For example, if the current instance represents <c>2000-01-01</c>,
/// there is one year until <c>2001-01-01</c>.
/// </remarks>
public int YearsUntil(Date date)
{
if (this == date)
{
return 0;
}
int years = date.Year - this.Year;
var d = date.AddYears(-years);
if (date > this)
{
if (this > d)
{
years--;
}
}
else
{
if (this < d)
{
years++;
}
}
return years;
}
/// <summary>
/// Returns the number of whole years elapsed from the <paramref name="date"/> specified to this date.
/// If the <paramref name="date"/> has not yet passed, the result will be negative.
/// </summary>
/// <param name="date">The target <see cref="Date"/> value.</param>
/// <returns>The integer number of whole years since the date specified.</returns>
/// <remarks>
/// This operation uses an exclusive upper bound.
/// For example, if the current instance represents <c>2001-01-01</c>,
/// there has been one year since <c>2000-01-01</c>.
/// </remarks>
public int YearsSince(Date date)
{
return date.YearsUntil(this);
}
/// <summary>
/// Determines if a date falls within the range provided.
/// </summary>
/// <param name="startDate">The starting date, inclusive.</param>
/// <param name="endDate">
/// The ending date, either inclusive or exclusive, depending on the value of
/// <paramref name="exclusiveEndDate"/>.
/// </param>
/// <param name="exclusiveEndDate">
/// If true, then the <paramref name="endDate"/> is treated as exclusive.
/// Otherwise, the <paramref name="endDate"/> is treated as inclusive.
/// The default is <c>false</c> (inclusive).
/// </param>
/// <returns>True, if the date falls within the range, false otherwise.</returns>
/// <remarks>
/// Because a <see cref="Date"/> is intended to represent a whole calendar date,
/// this operation is inclusive by default. For example, January 7th would be
/// considered to be included in the week of January 1st through January 7th.
/// If you desire the end date to be excluded, then set the <paramref name="exclusiveEndDate"/>
/// parameter to <c>true</c>.
/// </remarks>
public bool IsBetween(Date startDate, Date endDate, bool exclusiveEndDate = false)
{
return this >= startDate && (this < endDate || (this == endDate && !exclusiveEndDate));
}
/// <summary>
/// Compares two instances of <see cref="Date"/> and returns an integer that indicates whether the first
/// instance is earlier than, the same as, or later than the second instance.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns>
/// A signed number indicating the relative values of <paramref name="left"/> and <paramref name="right"/>.
/// <list type="table">
/// <listheader><term>Value</term><term>Description</term></listheader>
/// <item>
/// <term>Less than zero</term>
/// <term><paramref name="left"/> is earlier than <paramref name="right"/>.</term>
/// </item>
/// <item>
/// <term>Zero</term>
/// <term><paramref name="left"/> is the same as <paramref name="right"/>.</term>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <term><paramref name="left"/> is later than <paramref name="right"/>.</term>
/// </item>
/// </list>
/// </returns>
public static int Compare(Date left, Date right)
{
if (left._dayNumber > right._dayNumber)
{
return 1;
}
if (left._dayNumber < right._dayNumber)
{
return -1;
}
return 0;
}
/// <summary>
/// Compares the value of this instance to a specified <see cref="Date"/> value and returns an integer that
/// indicates whether this instance is earlier than, the same as, or later than the specified
/// <see cref="Date"/> value.
/// </summary>
/// <param name="value">The object to compare to the current instance.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and the <paramref name="value"/> parameter.
/// <list type="table">
/// <listheader><term>Value</term><term>Description</term></listheader>
/// <item>
/// <term>Less than zero</term>
/// <term>This instance is earlier than <paramref name="value"/>.</term>
/// </item>
/// <item>
/// <term>Zero</term>
/// <term>This instance is the same as <paramref name="value"/>.</term>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <term>This instance is later than <paramref name="value"/>.</term>
/// </item>
/// </list>
/// </returns>
public int CompareTo(Date value)
{
return Compare(this, value);
}
/// <summary>
/// Compares the value of this instance to a specified object that contains a <see cref="Date"/> value and
/// returns an integer that indicates whether this instance is earlier than, the same as, or later than the
/// specified <see cref="Date"/> value.
/// </summary>
/// <param name="value">The object to compare to the current instance.</param>
/// <returns>
/// A signed number indicating the relative values of this instance and the <paramref name="value"/> parameter.
/// <list type="table">
/// <listheader><term>Value</term><term>Description</term></listheader>
/// <item>
/// <term>Less than zero</term>
/// <term>This instance is earlier than <paramref name="value"/>.</term>
/// </item>
/// <item>
/// <term>Zero</term>
/// <term>This instance is earlier than <paramref name="value"/>.</term>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <term>
/// This instance is later than <paramref name="value"/>,
/// or <paramref name="value"/> is <c>null</c>.
/// </term>
/// </item>
/// </list>
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="value"/> is not a <see cref="Date"/>.
/// </exception>
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (!(value is Date))
{
throw new ArgumentException(Strings.Argument_MustBeDate, nameof(value));
}
return Compare(this, (Date)value);
}
/// <summary>
/// Returns a value indicating whether two <see cref="Date"/> instances have the same date value.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns><c>true</c> if the two values are equal; otherwise, <c>false</c>.</returns>
public static bool Equals(Date left, Date right)
{
return left.Equals(right);
}
/// <summary>
/// Returns a value indicating whether the value of this instance is equal to the value of the specified
/// <see cref="Date"/> instance.
/// </summary>
/// <param name="value">The other <see cref="Date"/> object to compare against this instance.</param>
/// <returns>
/// <c>true</c> if the <paramref name="value"/> parameter equals the value of this instance;
/// otherwise, <c>false</c>.
/// </returns>
public bool Equals(Date value)
{
return _dayNumber == value._dayNumber;
}
/// <summary>
/// Returns a value indicating whether this instance is equal to the specified object.
/// </summary>
/// <param name="value">The object to compare to this instance.</param>
/// <returns>
/// <c>true</c> if <paramref name="value"/> is an instance of <see cref="Date"/>
/// and equals the value of this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object value)
{
if (ReferenceEquals(null, value))
{
return false;
}
return value is Date date && Equals(date);
}
/// <summary>
/// Returns the hash code of this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
/// <remarks>
/// The hash code of a <see cref="Date"/> object is the day number, which is the
/// number of days since January 1, 0001 in the proleptic Gregorian calendar.
/// </remarks>
public override int GetHashCode()
{
return _dayNumber;
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent string representation.
/// </summary>
/// <returns>A string representation of value of the current <see cref="Date"/> object.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// The date is outside the range of dates supported by the calendar used by the current culture.
/// </exception>
public override string ToString()
{
Contract.Ensures(Contract.Result<string>() != null);
return ToDateTimeAtMidnight().ToString("d");
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent string representation
/// using the specified culture-specific format information.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>
/// A string representation of value of the current <see cref="Date"/> object as specified by
/// <paramref name="provider"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// The date is outside the range of dates supported by the calendar used by <paramref name="provider"/>.
/// </exception>
public string ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<string>() != null);
return ToDateTimeAtMidnight().ToString("d", provider);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent string representation
/// using the specified format.
/// </summary>
/// <param name="format">A standard or custom date format string.</param>
/// <returns>
/// A string representation of value of the current <see cref="Date"/> object as specified by
/// <paramref name="format"/>.
/// </returns>
/// <exception cref="FormatException">
/// The length of <paramref name="format"/> is 1, and it is not one of the format specifier characters defined
/// for <see cref="DateTimeFormatInfo"/>.
/// <para>-or-</para>
/// <paramref name="format"/> does not contain a valid custom format pattern.
/// <para>-or-</para>
/// The standard or custom format specified is not valid for a <see cref="Date"/> object, because it contains
/// a time-of-day component.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The date is outside the range of dates supported by the calendar used by the current culture.
/// </exception>
public string ToString(string format)
{
Contract.Ensures(Contract.Result<string>() != null);
format = NormalizeDateFormat(format);
return ToDateTimeAtMidnight().ToString(format);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent string representation
/// using the specified format and culture-specific format information.
/// </summary>
/// <param name="format">A standard or custom date format string.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>
/// A string representation of value of the current <see cref="Date"/> object as specified by
/// <paramref name="format"/> and <paramref name="provider"/>.
/// </returns>
/// <exception cref="FormatException">
/// The length of <paramref name="format"/> is 1, and it is not one of the format specifier characters defined
/// for <see cref="DateTimeFormatInfo"/>.
/// <para>-or-</para>
/// <paramref name="format"/> does not contain a valid custom format pattern.
/// <para>-or-</para>
/// The standard or custom format specified is not valid for a <see cref="Date"/> object, because it contains
/// a time-of-day component.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The date is outside the range of dates supported by the calendar used by <paramref name="provider"/>.
/// </exception>
public string ToString(string format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<string>() != null);
format = NormalizeDateFormat(format);
return ToDateTimeAtMidnight().ToString(format, provider);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent long date string
/// representation.
/// </summary>
/// <returns>
/// A string that contains the long date string representation of the current <see cref="Date"/> object.
/// </returns>
/// <remarks>
/// The value of the current <see cref="Date"/> object is formatted using the pattern defined by the
/// <see cref="DateTimeFormatInfo.LongDatePattern" /> property associated with the current thread culture.
/// </remarks>
public string ToLongDateString()
{
return ToString(CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent long date string
/// representation.
/// </summary>
/// <returns>
/// A string that contains the long date string representation of the current <see cref="Date"/> object.
/// </returns>
/// <remarks>
/// The value of the current <see cref="Date"/> object is formatted using the pattern defined by the
/// <see cref="DateTimeFormatInfo.LongDatePattern" /> property associated with the invariant culture.
/// </remarks>
public string ToLongDateStringInvariant()
{
return ToString(CultureInfo.InvariantCulture.DateTimeFormat.LongDatePattern, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent short date string
/// representation.
/// </summary>
/// <returns>
/// A string that contains the short date string representation of the current <see cref="Date"/> object.
/// </returns>
/// <remarks>
/// The value of the current <see cref="Date"/> object is formatted using the pattern defined by the
/// <see cref="DateTimeFormatInfo.ShortDatePattern" /> property associated with the current thread culture.
/// </remarks>
public string ToShortDateString()
{
return ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent short date string
/// representation.
/// </summary>
/// <returns>
/// A string that contains the short date string representation of the current <see cref="Date"/> object.
/// </returns>
/// <remarks>
/// The value of the current <see cref="Date"/> object is formatted using the pattern defined by the
/// <see cref="DateTimeFormatInfo.ShortDatePattern" /> property associated with the invariant culture.
/// </remarks>
public string ToShortDateStringInvariant()
{
return ToString(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the value of the current <see cref="Date"/> object to its equivalent ISO standard string
/// representation (ISO-8601), which has the format: <c>yyyy-MM-dd</c>.
/// </summary>
/// <returns>
/// A string that contains the ISO standard string representation of the current <see cref="Date"/> object.
/// </returns>
/// <remarks>
/// Because the ISO-8601 standard uses the proleptic Gregorian calendar, this method always uses the calendar
/// of the <see cref="CultureInfo.InvariantCulture"/>, despite the setting of the current culture.
/// </remarks>
public string ToIsoString()
{
return ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the string representation of a date to its <see cref="Date"/> equivalent.
/// </summary>
/// <param name="s">A string that contains a date to convert.</param>
/// <returns>An object that is equivalent to the date contained in <paramref name="s"/>.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="s"/> is <c>null</c>.
/// </exception>
/// <exception cref="FormatException">
/// <paramref name="s"/> does not contain a valid string representation of a date.
/// </exception>
public static Date Parse(string s)
{
DateTime dt = DateTime.Parse(s);
return DateFromDateTime(dt);
}
/// <summary>
/// Converts the string representation of a date to its <see cref="Date"/> equivalent