/
TimeZoneInfo.cs
2226 lines (1953 loc) · 102 KB
/
TimeZoneInfo.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security;
using System.Threading;
namespace System
{
//
// DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset.
// These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in. To avoid this
// unwanted behavior in DateTime public APIs, DateTime internally passes the
// TimeZoneInfoOptions.NoThrowOnInvalidTime flag to internal TimeZoneInfo APIs.
//
// In the future we can consider exposing similar options on the public TimeZoneInfo APIs if there is enough
// demand for this alternate behavior.
//
[Flags]
internal enum TimeZoneInfoOptions
{
None = 1,
NoThrowOnInvalidTime = 2
}
[Serializable]
[TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo?>, ISerializable, IDeserializationCallback
{
private enum TimeZoneInfoResult
{
Success = 0,
TimeZoneNotFoundException = 1,
InvalidTimeZoneException = 2,
SecurityException = 3
}
private const int MaxKeyLength = 255;
private readonly string _id;
private string? _displayName;
private string? _standardDisplayName;
private string? _daylightDisplayName;
private readonly TimeSpan _baseUtcOffset;
private readonly bool _supportsDaylightSavingTime;
private readonly AdjustmentRule[]? _adjustmentRules;
// As we support IANA and Windows IDs, it is possible we create equivalent zone objects which differ only in the IDs.
private List<TimeZoneInfo>? _equivalentZones;
// constants for TimeZoneInfo.Local and TimeZoneInfo.Utc
private const string UtcId = "UTC";
private const string LocalId = "Local";
private static readonly TimeZoneInfo s_utcTimeZone = CreateUtcTimeZone();
private static CachedData s_cachedData = new CachedData();
//
// All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
//
// For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,
// there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local.
//
private sealed partial class CachedData
{
private volatile TimeZoneInfo? _localTimeZone;
private TimeZoneInfo CreateLocal()
{
lock (this)
{
TimeZoneInfo? timeZone = _localTimeZone;
if (timeZone == null)
{
timeZone = GetLocalTimeZone(this);
// this step is to break the reference equality
// between TimeZoneInfo.Local and a second time zone
// such as "Pacific Standard Time"
timeZone = new TimeZoneInfo(
timeZone._id,
timeZone._baseUtcOffset,
timeZone.DisplayName,
timeZone.StandardName,
timeZone.DaylightName,
timeZone._adjustmentRules,
disableDaylightSavingTime: false,
timeZone.HasIanaId);
_localTimeZone = timeZone;
}
return timeZone;
}
}
public TimeZoneInfo Local => _localTimeZone ?? CreateLocal();
/// <summary>
/// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo.
/// </summary>
public DateTimeKind GetCorrespondingKind(TimeZoneInfo? timeZone)
{
// We check reference equality to see if 'this' is the same as
// TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to
// support setting the DateTime Kind property to 'Local' or
// 'Utc' on the ConvertTime(...) return value.
//
// Using reference equality instead of value equality was a
// performance based design compromise. The reference equality
// has much greater performance, but it reduces the number of
// returned DateTime's that can be properly set as 'Local' or 'Utc'.
//
// For example, the user could be converting to the TimeZoneInfo returned
// by FindSystemTimeZoneById("Pacific Standard Time") and their local
// machine may be in Pacific time. If we used value equality to determine
// the corresponding Kind then this conversion would be tagged as 'Local';
// where as we are currently tagging the returned DateTime as 'Unspecified'
// in this example. Only when the user passes in TimeZoneInfo.Local or
// TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.
//
return
ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc :
ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local :
DateTimeKind.Unspecified;
}
public Dictionary<string, TimeZoneInfo>? _systemTimeZones;
public ReadOnlyCollection<TimeZoneInfo>? _readOnlySystemTimeZones;
public ReadOnlyCollection<TimeZoneInfo>? _readOnlyUnsortedSystemTimeZones;
public Dictionary<string, TimeZoneInfo>? _timeZonesUsingAlternativeIds;
public bool _allSystemTimeZonesRead;
}
// used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2);
public string Id => _id;
/// <summary>
/// Returns true if this TimeZoneInfo object has an IANA ID.
/// </summary>
public bool HasIanaId { get; }
public string DisplayName
{
get
{
if (_displayName == null)
Interlocked.CompareExchange(ref _displayName, PopulateDisplayName(), null);
return _displayName ?? string.Empty;
}
}
public string StandardName
{
get
{
if (_standardDisplayName == null)
Interlocked.CompareExchange(ref _standardDisplayName, PopulateStandardDisplayName(), null);
return _standardDisplayName ?? string.Empty;
}
}
public string DaylightName
{
get
{
if (_daylightDisplayName == null)
Interlocked.CompareExchange(ref _daylightDisplayName, PopulateDaylightDisplayName(), null);
return _daylightDisplayName ?? string.Empty;
}
}
public TimeSpan BaseUtcOffset => _baseUtcOffset;
public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime;
/// <summary>
/// Returns an array of TimeSpan objects representing all of
/// the possible UTC offset values for this ambiguous time.
/// </summary>
public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset)
{
if (!SupportsDaylightSavingTime)
{
throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
}
DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;
bool isAmbiguous = false;
AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out int? ruleIndex);
if (rule != null && rule.HasDaylightSaving)
{
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
if (!isAmbiguous)
{
throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
TimeSpan[] timeSpans = new TimeSpan[2];
TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;
// the TimeSpan array must be sorted from least to greatest
if (rule.DaylightDelta > TimeSpan.Zero)
{
timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
}
else
{
timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
}
return timeSpans;
}
/// <summary>
/// Returns an array of TimeSpan objects representing all of
/// possible UTC offset values for this ambiguous time.
/// </summary>
public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime)
{
if (!SupportsDaylightSavingTime)
{
throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
}
DateTime adjustedTime;
if (dateTime.Kind == DateTimeKind.Local)
{
CachedData cachedData = s_cachedData;
adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
}
else if (dateTime.Kind == DateTimeKind.Utc)
{
CachedData cachedData = s_cachedData;
adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
}
else
{
adjustedTime = dateTime;
}
bool isAmbiguous = false;
AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out int? ruleIndex);
if (rule != null && rule.HasDaylightSaving)
{
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
if (!isAmbiguous)
{
throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
TimeSpan[] timeSpans = new TimeSpan[2];
TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;
// the TimeSpan array must be sorted from least to greatest
if (rule.DaylightDelta > TimeSpan.Zero)
{
timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
}
else
{
timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
}
return timeSpans;
}
// note the time is already adjusted
private AdjustmentRule? GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex)
{
AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving)
{
// When using NoDaylightTransitions rules, each rule is only for one offset.
// When looking for the Daylight savings rules, and we found the non-DST rule,
// then we get the rule right before this rule.
return GetPreviousAdjustmentRule(rule, ruleIndex);
}
return rule;
}
/// <summary>
/// Gets the AdjustmentRule that is immediately preceding the specified rule.
/// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,
/// then the specified rule is returned.
/// </summary>
private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex)
{
Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules.");
Debug.Assert(_adjustmentRules != null);
if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length)
{
return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1];
}
AdjustmentRule result = rule;
for (int i = 1; i < _adjustmentRules.Length; i++)
{
// use ReferenceEquals here instead of AdjustmentRule.Equals because
// ReferenceEquals is much faster. This is safe because all the callers
// of GetPreviousAdjustmentRule pass in a rule that was retrieved from
// _adjustmentRules. A different approach will be needed if this ever changes.
if (ReferenceEquals(rule, _adjustmentRules[i]))
{
result = _adjustmentRules[i - 1];
break;
}
}
return result;
}
/// <summary>
/// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
/// </summary>
public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) =>
GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
/// <summary>
/// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
/// </summary>
public TimeSpan GetUtcOffset(DateTime dateTime) =>
GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
// Shortcut for TimeZoneInfo.Local.GetUtcOffset
internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
{
CachedData cachedData = s_cachedData;
return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData);
}
/// <summary>
/// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
/// </summary>
internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) =>
GetUtcOffset(dateTime, flags, s_cachedData);
private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
{
if (dateTime.Kind == DateTimeKind.Local)
{
if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local)
{
//
// normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
//
DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
return GetUtcOffsetFromUtc(adjustedTime, this);
}
//
// Fall through for TimeZoneInfo.Local.GetUtcOffset(date)
// to handle an edge case with Invalid-Times for DateTime formatting:
//
// Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00"
//
// By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc
// the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an
// interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output:
//
// 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00"
// 2) converted to UTC "2007-03-11T10:00:00.0000000Z"
// 3) offset returned "2007-03-11T03:00:00.0000000-07:00"
//
}
else if (dateTime.Kind == DateTimeKind.Utc)
{
if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
{
return _baseUtcOffset;
}
else
{
//
// passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
// special Loss-Less case.
//
return GetUtcOffsetFromUtc(dateTime, this);
}
}
return GetUtcOffset(dateTime, this);
}
/// <summary>
/// Returns true if the time is during the ambiguous time period
/// for the current TimeZoneInfo instance.
/// </summary>
public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset)
{
if (!_supportsDaylightSavingTime)
{
return false;
}
DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this);
return IsAmbiguousTime(adjustedTime.DateTime);
}
/// <summary>
/// Returns true if the time is during the ambiguous time period
/// for the current TimeZoneInfo instance.
/// </summary>
public bool IsAmbiguousTime(DateTime dateTime) =>
IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
/// <summary>
/// Returns true if the time is during the ambiguous time period
/// for the current TimeZoneInfo instance.
/// </summary>
internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags)
{
if (!_supportsDaylightSavingTime)
{
return false;
}
CachedData cachedData = s_cachedData;
DateTime adjustedTime =
dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) :
dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) :
dateTime;
AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out int? ruleIndex);
if (rule != null && rule.HasDaylightSaving)
{
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
return false;
}
/// <summary>
/// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
/// </summary>
public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset)
{
GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out bool isDaylightSavingTime);
return isDaylightSavingTime;
}
/// <summary>
/// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
/// </summary>
public bool IsDaylightSavingTime(DateTime dateTime) =>
IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
/// <summary>
/// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
/// </summary>
internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) =>
IsDaylightSavingTime(dateTime, flags, s_cachedData);
private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
{
//
// dateTime.Kind is UTC, then time will be converted from UTC
// into current instance's timezone
// dateTime.Kind is Local, then time will be converted from Local
// into current instance's timezone
// dateTime.Kind is UnSpecified, then time is already in
// current instance's timezone
//
// Our DateTime handles ambiguous times, (one is in the daylight and
// one is in standard.) If a new DateTime is constructed during ambiguous
// time, it is defaulted to "Standard" (i.e. this will return false).
// For Invalid times, we will return false
if (!_supportsDaylightSavingTime || _adjustmentRules == null)
{
return false;
}
DateTime adjustedTime;
//
// handle any Local/Utc special cases...
//
if (dateTime.Kind == DateTimeKind.Local)
{
adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
}
else if (dateTime.Kind == DateTimeKind.Utc)
{
if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
{
// simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags);
return false;
}
else
{
//
// passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
// special Loss-Less case.
//
GetUtcOffsetFromUtc(dateTime, this, out bool isDaylightSavings);
return isDaylightSavings;
}
}
else
{
adjustedTime = dateTime;
}
//
// handle the normal cases...
//
AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out int? ruleIndex);
if (rule != null && rule.HasDaylightSaving)
{
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
return GetIsDaylightSavings(adjustedTime, rule, daylightTime);
}
else
{
return false;
}
}
/// <summary>
/// Returns true when dateTime falls into a "hole in time".
/// </summary>
public bool IsInvalidTime(DateTime dateTime)
{
bool isInvalid = false;
if ((dateTime.Kind == DateTimeKind.Unspecified) ||
(dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))
{
// only check Unspecified and (Local when this TimeZoneInfo instance is Local)
AdjustmentRule? rule = GetAdjustmentRuleForTime(dateTime, out int? ruleIndex);
if (rule != null && rule.HasDaylightSaving)
{
DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex);
isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
}
else
{
isInvalid = false;
}
}
return isInvalid;
}
/// <summary>
/// Clears data from static members.
/// </summary>
public static void ClearCachedData()
{
// Clear a fresh instance of cached data
s_cachedData = new CachedData();
}
/// <summary>
/// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
/// </summary>
public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) =>
ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
/// <summary>
/// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
/// </summary>
public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) =>
ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
/// <summary>
/// Helper function for retrieving a <see cref="TimeZoneInfo"/> object by time zone name.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order.
///
/// This function will either return a valid <see cref="TimeZoneInfo"/> instance or
/// it will throw <see cref="InvalidTimeZoneException"/> / <see cref="TimeZoneNotFoundException"/> /
/// <see cref="SecurityException"/>
/// </summary>
/// <param name="id">Time zone name.</param>
/// <returns>Valid <see cref="TimeZoneInfo"/> instance.</returns>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
TimeZoneInfo? value;
Exception? e;
TimeZoneInfoResult result = TryFindSystemTimeZoneById(id, out value, out e);
switch (result)
{
case TimeZoneInfoResult.Success:
return value!;
case TimeZoneInfoResult.InvalidTimeZoneException:
Debug.Assert(e is InvalidTimeZoneException,
"TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
throw e;
case TimeZoneInfoResult.SecurityException:
throw new SecurityException(SR.Format(SR.Security_CannotReadFileData, id), e);
default:
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
/// <summary>
/// Helper function for retrieving a <see cref="TimeZoneInfo"/> object by time zone name.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order.
///
/// This function will either return <c>true</c> and a valid <see cref="TimeZoneInfo"/>
/// instance or return <c>false</c> and <c>null</c>.
/// </summary>
/// <param name="id">Time zone name.</param>
/// <param name="timeZoneInfo">A valid retrieved <see cref="TimeZoneInfo"/> or <c>null</c>.</param>
/// <returns><c>true</c> if the <see cref="TimeZoneInfo"/> object was successfully retrieved, <c>false</c> otherwise.</returns>
public static bool TryFindSystemTimeZoneById(string id, [NotNullWhenAttribute(true)] out TimeZoneInfo? timeZoneInfo)
=> TryFindSystemTimeZoneById(id, out timeZoneInfo, out _) == TimeZoneInfoResult.Success;
/// <summary>
/// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order.
///
/// This function will either return:
/// <c>TimeZoneInfoResult.Success</c> and a valid <see cref="TimeZoneInfo"/>instance and <c>null</c> Exception or
/// <c>TimeZoneInfoResult.TimeZoneNotFoundException</c> and <c>null</c> <see cref="TimeZoneInfo"/> and Exception (can be null) or
/// other <c>TimeZoneInfoResult</c> and <c>null</c> <see cref="TimeZoneInfo"/> and valid Exception.
/// </summary>
private static TimeZoneInfoResult TryFindSystemTimeZoneById(string id, out TimeZoneInfo? timeZone, out Exception? e)
{
// Special case for Utc as it will not exist in the dictionary with the rest
// of the system time zones. There is no need to do this check for Local.Id
// since Local is a real time zone that exists in the dictionary cache
if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
{
timeZone = Utc;
e = default;
return TimeZoneInfoResult.Success;
}
ArgumentNullException.ThrowIfNull(id);
if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))
{
timeZone = default;
e = default;
return TimeZoneInfoResult.TimeZoneNotFoundException;
}
CachedData cachedData = s_cachedData;
lock (cachedData)
{
return TryGetTimeZone(id, out timeZone, out e, cachedData);
}
}
/// <summary>
/// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
/// </summary>
public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
{
if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase))
{
// TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData.
// Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.
// Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't
// be reference equal to the new TimeZoneInfo.Local
//
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
}
else if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase))
{
return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData);
}
else
{
return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));
}
}
/// <summary>
/// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
/// </summary>
public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
{
ArgumentNullException.ThrowIfNull(destinationTimeZone);
// calculate the destination time zone offset
DateTime utcDateTime = dateTimeOffset.UtcDateTime;
TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);
// check for overflow
long ticks = utcDateTime.Ticks + destinationOffset.Ticks;
return
ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue :
ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue :
new DateTimeOffset(ticks, destinationOffset);
}
/// <summary>
/// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
/// </summary>
public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone)
{
ArgumentNullException.ThrowIfNull(destinationTimeZone);
// Special case to give a way clearing the cache without exposing ClearCachedData()
if (dateTime.Ticks == 0)
{
ClearCachedData();
}
CachedData cachedData = s_cachedData;
TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local;
return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
/// <summary>
/// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
/// </summary>
public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) =>
ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
/// <summary>
/// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
/// </summary>
internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) =>
ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData)
{
ArgumentNullException.ThrowIfNull(sourceTimeZone);
ArgumentNullException.ThrowIfNull(destinationTimeZone);
DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
{
throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone));
}
//
// check to see if the DateTime is in an invalid time range. This check
// requires the current AdjustmentRule and DaylightTime - which are also
// needed to calculate 'sourceOffset' in the normal conversion case.
// By calculating the 'sourceOffset' here we improve the
// performance for the normal case at the expense of the 'ArgumentException'
// case and Loss-less Local special cases.
//
AdjustmentRule? sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out int? sourceRuleIndex);
TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;
if (sourceRule != null)
{
sourceOffset += sourceRule.BaseUtcOffsetDelta;
if (sourceRule.HasDaylightSaving)
{
DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule, sourceRuleIndex);
// 'dateTime' might be in an invalid time range since it is in an AdjustmentRule
// period that supports DST
if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))
{
throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime));
}
bool sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime);
// adjust the sourceOffset according to the Adjustment Rule / Daylight Saving Rule
sourceOffset += (sourceIsDaylightSavings ? sourceRule.DaylightDelta : TimeSpan.Zero /*FUTURE: sourceRule.StandardDelta*/);
}
}
DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone);
// handle the special case of Loss-less Local->Local and UTC->UTC)
if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind)
{
return dateTime;
}
long utcTicks = dateTime.Ticks - sourceOffset.Ticks;
// handle the normal case by converting from 'source' to UTC and then to 'target'
DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out bool isAmbiguousLocalDst);
if (targetKind == DateTimeKind.Local)
{
// Because the ticks conversion between UTC and local is lossy, we need to capture whether the
// time is in a repeated hour so that it can be passed to the DateTime constructor.
return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);
}
else
{
return new DateTime(targetConverted.Ticks, targetKind);
}
}
/// <summary>
/// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone.
/// </summary>
public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) =>
ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
/// <summary>
/// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
/// </summary>
public static DateTime ConvertTimeToUtc(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime;
}
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
}
/// <summary>
/// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
/// </summary>
internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
{
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime;
}
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);
}
/// <summary>
/// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
/// </summary>
public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) =>
ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData);
/// <summary>
/// Returns value equality. Equals does not compare any localizable
/// String objects (DisplayName, StandardName, DaylightName).
/// </summary>
public bool Equals([NotNullWhen(true)] TimeZoneInfo? other) =>
other != null &&
string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) &&
HasSameRules(other);
public override bool Equals([NotNullWhen(true)] object? obj) => Equals(obj as TimeZoneInfo);
public static TimeZoneInfo FromSerializedString(string source)
{
ArgumentNullException.ThrowIfNull(source);
if (source.Length == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));
}
return StringSerializer.GetDeserializedTimeZoneInfo(source);
}
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id);
/// <summary>
/// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's
/// from the local machine. The entries in the collection are sorted by
/// <see cref="DisplayName"/>.
/// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.
/// </summary>
public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones() => GetSystemTimeZones(skipSorting: false);
/// <summary>
/// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's from the local machine.
/// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.
/// </summary>
/// <param name="skipSorting">If true, The collection returned may not necessarily be sorted.</param>
/// <remarks>By setting the skipSorting parameter to true, the method will attempt to avoid sorting the returned collection.
/// This option can be beneficial when the caller does not require a sorted list and aims to enhance the performance. </remarks>
public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones(bool skipSorting)
{
CachedData cachedData = s_cachedData;
lock (cachedData)
{
if ((skipSorting ? cachedData._readOnlyUnsortedSystemTimeZones : cachedData._readOnlySystemTimeZones) is null)
{
if (!cachedData._allSystemTimeZonesRead)
{
PopulateAllSystemTimeZones(cachedData);
cachedData._allSystemTimeZonesRead = true;
}
if (cachedData._systemTimeZones != null)
{
// return a collection of the cached system time zones
TimeZoneInfo[] array = new TimeZoneInfo[cachedData._systemTimeZones.Count];
cachedData._systemTimeZones.Values.CopyTo(array, 0);
if (!skipSorting)
{
// sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
Array.Sort(array, static (x, y) =>
{
// sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
});
// Always reset _readOnlyUnsortedSystemTimeZones even if it was initialized before. This prevents the need to maintain two separate cache lists in memory
// and guarantees that if _readOnlySystemTimeZones is initialized, _readOnlyUnsortedSystemTimeZones is also initialized.
cachedData._readOnlySystemTimeZones = cachedData._readOnlyUnsortedSystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(array);
}
else
{
cachedData._readOnlyUnsortedSystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(array);
}
}
else
{
cachedData._readOnlySystemTimeZones = cachedData._readOnlyUnsortedSystemTimeZones = ReadOnlyCollection<TimeZoneInfo>.Empty;
}
}
}
return skipSorting ? cachedData._readOnlyUnsortedSystemTimeZones! : cachedData._readOnlySystemTimeZones!;
}
/// <summary>
/// Value equality on the "adjustmentRules" array
/// </summary>
public bool HasSameRules(TimeZoneInfo other)
{
ArgumentNullException.ThrowIfNull(other);
// check the utcOffset and supportsDaylightSavingTime members
if (_baseUtcOffset != other._baseUtcOffset ||
_supportsDaylightSavingTime != other._supportsDaylightSavingTime)
{
return false;
}
AdjustmentRule[]? currentRules = _adjustmentRules;
AdjustmentRule[]? otherRules = other._adjustmentRules;
if (currentRules is null && otherRules is null)
{
return true;
}
return currentRules.AsSpan().SequenceEqual(otherRules);
}
/// <summary>
/// Returns a TimeZoneInfo instance that represents the local time on the machine.
/// Accessing this property may throw InvalidTimeZoneException or COMException
/// if the machine is in an unstable or corrupt state.
/// </summary>
public static TimeZoneInfo Local => s_cachedData.Local;
//
// ToSerializedString -
//
// "TimeZoneInfo" := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N]
//
// "TimeZoneInfo Data" := <_id>;<_baseUtcOffset>;<_displayName>;
// <_standardDisplayName>;<_daylightDispayName>;
//
// "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>;
// [TransitionTime Data DST Start]
// [TransitionTime Data DST End]
//
// "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day>
//
public string ToSerializedString() => StringSerializer.GetSerializedString(this);
/// <summary>
/// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US & Canada); Tijuana"
/// </summary>
public override string ToString() => DisplayName;
/// <summary>
/// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)
/// </summary>
public static TimeZoneInfo Utc => s_utcTimeZone;
private TimeZoneInfo(