-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
timezoneinfo.cs
4159 lines (3542 loc) · 184 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
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: TimeZoneInfo
**
**
** Purpose:
** This class is used to represent a Dynamic TimeZone. It
** has methods for converting a DateTime between TimeZones,
** and for reading TimeZone data from the Windows Registry
**
**
============================================================*/
namespace System {
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
//
// 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]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
[TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
sealed public class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback {
// ---- SECTION: members supporting exposed properties -------------*
private String m_id;
private String m_displayName;
private String m_standardDisplayName;
private String m_daylightDisplayName;
private TimeSpan m_baseUtcOffset;
private Boolean m_supportsDaylightSavingTime;
private AdjustmentRule[] m_adjustmentRules;
// ---- SECTION: members for internal support ---------*
private enum TimeZoneInfoResult {
Success = 0,
TimeZoneNotFoundException = 1,
InvalidTimeZoneException = 2,
SecurityException = 3
};
#if FEATURE_WIN32_REGISTRY
// registry constants for the 'Time Zones' hive
//
private const string c_timeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
private const string c_timeZonesRegistryHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_timeZonesRegistryHive;
private const string c_displayValue = "Display";
private const string c_daylightValue = "Dlt";
private const string c_standardValue = "Std";
private const string c_muiDisplayValue = "MUI_Display";
private const string c_muiDaylightValue = "MUI_Dlt";
private const string c_muiStandardValue = "MUI_Std";
private const string c_timeZoneInfoValue = "TZI";
private const string c_firstEntryValue = "FirstEntry";
private const string c_lastEntryValue = "LastEntry";
#endif // FEATURE_WIN32_REGISTRY
// constants for TimeZoneInfo.Local and TimeZoneInfo.Utc
private const string c_utcId = "UTC";
private const string c_localId = "Local";
private const int c_maxKeyLength = 255;
private const int c_regByteLength = 44;
// Number of 100ns ticks per time unit
private const long c_ticksPerMillisecond = 10000;
private const long c_ticksPerSecond = c_ticksPerMillisecond * 1000;
private const long c_ticksPerMinute = c_ticksPerSecond * 60;
private const long c_ticksPerHour = c_ticksPerMinute * 60;
private const long c_ticksPerDay = c_ticksPerHour * 24;
private const long c_ticksPerDayRange = c_ticksPerDay - c_ticksPerMillisecond;
//
// 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.
//
#pragma warning disable 0420
class CachedData
{
private volatile TimeZoneInfo m_localTimeZone;
private volatile TimeZoneInfo m_utcTimeZone;
private TimeZoneInfo CreateLocal()
{
lock (this)
{
TimeZoneInfo timeZone = m_localTimeZone;
if (timeZone == null) {
timeZone = TimeZoneInfo.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.m_id,
timeZone.m_baseUtcOffset,
timeZone.m_displayName,
timeZone.m_standardDisplayName,
timeZone.m_daylightDisplayName,
timeZone.m_adjustmentRules,
false);
m_localTimeZone = timeZone;
}
return timeZone;
}
}
public TimeZoneInfo Local {
get {
TimeZoneInfo timeZone = m_localTimeZone;
if (timeZone == null) {
timeZone = CreateLocal();
}
return timeZone;
}
}
private TimeZoneInfo CreateUtc()
{
lock (this)
{
TimeZoneInfo timeZone = m_utcTimeZone;
if (timeZone == null) {
timeZone = CreateCustomTimeZone(c_utcId, TimeSpan.Zero, c_utcId, c_utcId);
m_utcTimeZone = timeZone;
}
return timeZone;
}
}
public TimeZoneInfo Utc {
get {
Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
TimeZoneInfo timeZone = m_utcTimeZone;
if (timeZone == null) {
timeZone = CreateUtc();
}
return timeZone;
}
}
//
// GetCorrespondingKind-
//
// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo
//
public DateTimeKind GetCorrespondingKind(TimeZoneInfo timeZone) {
DateTimeKind kind;
//
// 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 ConverTime(...) 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.
//
if ((object)timeZone == (object)m_utcTimeZone) {
kind = DateTimeKind.Utc;
}
else if ((object)timeZone == (object)m_localTimeZone) {
kind = DateTimeKind.Local;
}
else {
kind = DateTimeKind.Unspecified;
}
return kind;
}
#if FEATURE_WIN32_REGISTRY
public Dictionary<string, TimeZoneInfo> m_systemTimeZones;
public ReadOnlyCollection<TimeZoneInfo> m_readOnlySystemTimeZones;
public bool m_allSystemTimeZonesRead;
[System.Security.SecuritySafeCritical]
private static TimeZoneInfo GetCurrentOneYearLocal() {
// load the data from the OS
TimeZoneInfo match;
Win32Native.TimeZoneInformation timeZoneInformation = new Win32Native.TimeZoneInformation();
long result = UnsafeNativeMethods.GetTimeZoneInformation(out timeZoneInformation);
if (result == Win32Native.TIME_ZONE_ID_INVALID)
match = CreateCustomTimeZone(c_localId, TimeSpan.Zero, c_localId, c_localId);
else
match = GetLocalTimeZoneFromWin32Data(timeZoneInformation, false);
return match;
}
private volatile OffsetAndRule m_oneYearLocalFromUtc;
public OffsetAndRule GetOneYearLocalFromUtc(int year) {
OffsetAndRule oneYearLocFromUtc = m_oneYearLocalFromUtc;
if (oneYearLocFromUtc == null || oneYearLocFromUtc.year != year) {
TimeZoneInfo currentYear = GetCurrentOneYearLocal();
AdjustmentRule rule = currentYear.m_adjustmentRules == null ? null : currentYear.m_adjustmentRules[0];
oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
m_oneYearLocalFromUtc = oneYearLocFromUtc;
}
return oneYearLocFromUtc;
}
#endif // FEATURE_WIN32_REGISTRY
};
#pragma warning restore 0420
static CachedData s_cachedData = new CachedData();
private class OffsetAndRule {
public int year;
public TimeSpan offset;
public AdjustmentRule rule;
public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule) {
this.year = year;
this.offset = offset;
this.rule = rule;
}
}
// used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
private static DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
private static DateTime s_minDateOnly = new DateTime(1, 1, 2);
// ---- SECTION: public properties --------------*
public String Id {
get {
return m_id;
}
}
public String DisplayName {
get {
return (m_displayName == null ? String.Empty : m_displayName);
}
}
public String StandardName {
get {
return (m_standardDisplayName == null ? String.Empty : m_standardDisplayName);
}
}
public String DaylightName {
get {
return (m_daylightDisplayName == null? String.Empty : m_daylightDisplayName);
}
}
public TimeSpan BaseUtcOffset {
get {
return m_baseUtcOffset;
}
}
public Boolean SupportsDaylightSavingTime {
get {
return m_supportsDaylightSavingTime;
}
}
// ---- SECTION: public methods --------------*
//
// GetAdjustmentRules -
//
// returns a cloned array of AdjustmentRule objects
//
public AdjustmentRule [] GetAdjustmentRules() {
if (m_adjustmentRules == null) {
return new AdjustmentRule[0];
}
else {
return (AdjustmentRule[])m_adjustmentRules.Clone();
}
}
//
// GetAmbiguousTimeOffsets -
//
// returns an array of TimeSpan objects representing all of
// possible UTC offset values for this ambiguous time
//
public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) {
if (!SupportsDaylightSavingTime) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), "dateTimeOffset");
}
Contract.EndContractBlock();
DateTime adjustedTime = (TimeZoneInfo.ConvertTime(dateTimeOffset, this)).DateTime;
Boolean isAmbiguous = false;
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
if (!isAmbiguous) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), "dateTimeOffset");
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
TimeSpan[] timeSpans = new TimeSpan[2];
TimeSpan actualUtcOffset = m_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;
}
public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) {
if (!SupportsDaylightSavingTime) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), "dateTime");
}
Contract.EndContractBlock();
DateTime adjustedTime;
if (dateTime.Kind == DateTimeKind.Local) {
CachedData cachedData = s_cachedData;
adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
}
else if (dateTime.Kind == DateTimeKind.Utc) {
CachedData cachedData = s_cachedData;
adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Utc, this, TimeZoneInfoOptions.None, cachedData);
}
else {
adjustedTime = dateTime;
}
Boolean isAmbiguous = false;
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
if (!isAmbiguous) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), "dateTime");
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
TimeSpan[] timeSpans = new TimeSpan[2];
TimeSpan actualUtcOffset = m_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;
}
//
// GetUtcOffset -
//
// returns the Universal Coordinated Time (UTC) Offset
// for the current TimeZoneInfo instance.
//
public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) {
return GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
}
public TimeSpan GetUtcOffset(DateTime dateTime) {
return 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);
}
internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) {
return 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 = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, cachedData.Utc, 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 m_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, flags);
}
//
// IsAmbiguousTime -
//
// returns true if the time is during the ambiguous time period
// for the current TimeZoneInfo instance.
//
public Boolean IsAmbiguousTime(DateTimeOffset dateTimeOffset) {
if (!m_supportsDaylightSavingTime) {
return false;
}
DateTimeOffset adjustedTime = TimeZoneInfo.ConvertTime(dateTimeOffset, this);
return IsAmbiguousTime(adjustedTime.DateTime);
}
public Boolean IsAmbiguousTime(DateTime dateTime) {
return IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
internal Boolean IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags) {
if (!m_supportsDaylightSavingTime) {
return false;
}
DateTime adjustedTime;
if (dateTime.Kind == DateTimeKind.Local) {
CachedData cachedData = s_cachedData;
adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
}
else if (dateTime.Kind == DateTimeKind.Utc) {
CachedData cachedData = s_cachedData;
adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Utc, this, flags, cachedData);
}
else {
adjustedTime = dateTime;
}
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
}
return false;
}
//
// IsDaylightSavingTime -
//
// Returns true if the time is during Daylight Saving time
// for the current TimeZoneInfo instance.
//
public Boolean IsDaylightSavingTime(DateTimeOffset dateTimeOffset) {
Boolean isDaylightSavingTime;
GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime);
return isDaylightSavingTime;
}
public Boolean IsDaylightSavingTime(DateTime dateTime) {
return IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
}
internal Boolean IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) {
return IsDaylightSavingTime(dateTime, flags, s_cachedData);
}
private Boolean 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 (!m_supportsDaylightSavingTime || m_adjustmentRules == null) {
return false;
}
DateTime adjustedTime;
//
// handle any Local/Utc special cases...
//
if (dateTime.Kind == DateTimeKind.Local) {
adjustedTime = TimeZoneInfo.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.
//
Boolean isDaylightSavings;
GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings);
return isDaylightSavings;
}
}
else {
adjustedTime = dateTime;
}
//
// handle the normal cases...
//
AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime);
if (rule != null && rule.HasDaylightSaving) {
DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule);
return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags);
}
else {
return false;
}
}
//
// IsInvalidTime -
//
// returns true when dateTime falls into a "hole in time".
//
public Boolean IsInvalidTime(DateTime dateTime) {
Boolean 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);
if (rule != null && rule.HasDaylightSaving) {
DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule);
isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
}
else {
isInvalid = false;
}
}
return isInvalid;
}
//
// ClearCachedData -
//
// Clears data from static members
//
static public void ClearCachedData() {
// Clear a fresh instance of cached data
s_cachedData = new CachedData();
}
#if FEATURE_WIN32_REGISTRY
//
// ConvertTimeBySystemTimeZoneId -
//
// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone
//
static public DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, String destinationTimeZoneId) {
return ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
}
#endif // FEATURE_WIN32_REGISTRY
#if FEATURE_WIN32_REGISTRY
static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String destinationTimeZoneId) {
return ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
}
#endif // FEATURE_WIN32_REGISTRY
#if FEATURE_WIN32_REGISTRY
static public DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, String sourceTimeZoneId, String destinationTimeZoneId) {
if (dateTime.Kind == DateTimeKind.Local && String.Compare(sourceTimeZoneId, TimeZoneInfo.Local.Id, StringComparison.OrdinalIgnoreCase) == 0) {
// 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.Compare(sourceTimeZoneId, TimeZoneInfo.Utc.Id, StringComparison.OrdinalIgnoreCase) == 0) {
// TimeZoneInfo.Utc 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.Utc
//
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Utc, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
}
else {
return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));
}
}
#endif // FEATURE_WIN32_REGISTRY
//
// ConvertTime -
//
// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
//
static public DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) {
if (destinationTimeZone == null) {
throw new ArgumentNullException("destinationTimeZone");
}
Contract.EndContractBlock();
// calculate the destination time zone offset
DateTime utcDateTime = dateTimeOffset.UtcDateTime;
TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);
// check for overflow
Int64 ticks = utcDateTime.Ticks + destinationOffset.Ticks;
if (ticks > DateTimeOffset.MaxValue.Ticks) {
return DateTimeOffset.MaxValue;
}
else if (ticks < DateTimeOffset.MinValue.Ticks) {
return DateTimeOffset.MinValue;
}
else {
return new DateTimeOffset(ticks, destinationOffset);
}
}
static public DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
if (destinationTimeZone == null) {
throw new ArgumentNullException("destinationTimeZone");
}
Contract.EndContractBlock();
// Special case to give a way clearing the cache without exposing ClearCachedData()
if (dateTime.Ticks == 0) {
ClearCachedData();
}
CachedData cachedData = s_cachedData;
if (dateTime.Kind == DateTimeKind.Utc) {
return ConvertTime(dateTime, cachedData.Utc, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
else {
return ConvertTime(dateTime, cachedData.Local, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
}
static public DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) {
return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
}
static internal DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) {
return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
}
static private DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) {
if (sourceTimeZone == null) {
throw new ArgumentNullException("sourceTimeZone");
}
if (destinationTimeZone == null) {
throw new ArgumentNullException("destinationTimeZone");
}
Contract.EndContractBlock();
DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
if ( ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind) ) {
throw new ArgumentException(Environment.GetResourceString("Argument_ConvertMismatch"), "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);
TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;
if (sourceRule != null) {
sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta;
if (sourceRule.HasDaylightSaving) {
Boolean sourceIsDaylightSavings = false;
DaylightTimeStruct sourceDaylightTime = GetDaylightTime(dateTime.Year, sourceRule);
// '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(Environment.GetResourceString("Argument_DateTimeIsInvalid"), "dateTime");
}
sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);
// 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;
}
Int64 utcTicks = dateTime.Ticks - sourceOffset.Ticks;
// handle the normal case by converting from 'source' to UTC and then to 'target'
Boolean isAmbiguousLocalDst = false;
DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out 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);
}
}
//
// ConvertTimeFromUtc -
//
// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to
// the destinationTimeZone.
//
static public DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Utc, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
//
// ConvertTimeToUtc -
//
// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
//
static public DateTime ConvertTimeToUtc(DateTime dateTime) {
if (dateTime.Kind == DateTimeKind.Utc) {
return dateTime;
}
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, cachedData.Utc, TimeZoneInfoOptions.None, cachedData);
}
static internal DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags) {
if (dateTime.Kind == DateTimeKind.Utc) {
return dateTime;
}
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, cachedData.Local, cachedData.Utc, flags, cachedData);
}
static public DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) {
CachedData cachedData = s_cachedData;
return ConvertTime(dateTime, sourceTimeZone, cachedData.Utc, TimeZoneInfoOptions.None, cachedData);
}
//
// IEquatable.Equals -
//
// returns value equality. Equals does not compare any localizable
// String objects (DisplayName, StandardName, DaylightName).
//
public bool Equals(TimeZoneInfo other) {
return (other != null && String.Compare(this.m_id, other.m_id, StringComparison.OrdinalIgnoreCase) == 0 && HasSameRules(other));
}
public override bool Equals(object obj) {
TimeZoneInfo tzi = obj as TimeZoneInfo;
if (null == tzi) {
return false;
}
return Equals(tzi);
}
//
// FromSerializedString -
//
static public TimeZoneInfo FromSerializedString(string source) {
if (source == null) {
throw new ArgumentNullException("source");
}
if (source.Length == 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSerializedString", source), "source");
}
Contract.EndContractBlock();
return StringSerializer.GetDeserializedTimeZoneInfo(source);
}
//
// GetHashCode -
//
public override int GetHashCode() {
return m_id.ToUpper(CultureInfo.InvariantCulture).GetHashCode();
}
#if FEATURE_WIN32_REGISTRY
//
// GetSystemTimeZones -
//
// returns a ReadOnlyCollection<TimeZoneInfo> containing all valid TimeZone's
// from the local machine. The entries in the collection are sorted by
// 'DisplayName'.
//
// This method does *not* throw TimeZoneNotFoundException or
// InvalidTimeZoneException.
//
// <SecurityKernel Critical="True" Ring="0">
// <Asserts Name="Imperative: System.Security.PermissionSet" />
// </SecurityKernel>
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
static public ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones() {
CachedData cachedData = s_cachedData;
lock (cachedData) {
if (cachedData.m_readOnlySystemTimeZones == null) {
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
permSet.Assert();
using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(
c_timeZonesRegistryHive,
#if FEATURE_MACL
RegistryKeyPermissionCheck.Default,
System.Security.AccessControl.RegistryRights.ReadKey
#else
false
#endif
)) {
if (reg != null) {
foreach (string keyName in reg.GetSubKeyNames()) {
TimeZoneInfo value;
Exception ex;
TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
}
}
cachedData.m_allSystemTimeZonesRead = true;
}
List<TimeZoneInfo> list;
if (cachedData.m_systemTimeZones != null) {
// return a collection of the cached system time zones
list = new List<TimeZoneInfo>(cachedData.m_systemTimeZones.Values);
}
else {
// return an empty collection
list = new List<TimeZoneInfo>();
}
// sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
list.Sort(new TimeZoneInfoComparer());
cachedData.m_readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
}
}
return cachedData.m_readOnlySystemTimeZones;
}
#endif // FEATURE_WIN32_REGISTRY
//
// HasSameRules -
//
// Value equality on the "adjustmentRules" array
//
public Boolean HasSameRules(TimeZoneInfo other) {
if (other == null) {
throw new ArgumentNullException("other");
}
// check the utcOffset and supportsDaylightSavingTime members
Contract.EndContractBlock();
if (this.m_baseUtcOffset != other.m_baseUtcOffset
|| this.m_supportsDaylightSavingTime != other.m_supportsDaylightSavingTime) {
return false;
}
bool sameRules;
AdjustmentRule[] currentRules = this.m_adjustmentRules;
AdjustmentRule[] otherRules = other.m_adjustmentRules;
sameRules = (currentRules == null && otherRules == null)
||(currentRules != null && otherRules != null);
if (!sameRules) {
// AdjustmentRule array mismatch