/
TimeZoneInfo.cs
1568 lines (1295 loc) · 50.5 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
/*
* System.TimeZoneInfo
*
* Author(s)
* Stephane Delcroix <stephane@delcroix.org>
*
* Copyright 2011 Xamarin Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Text;
using System.Globalization;
using System.IO;
using Microsoft.Win32;
namespace System
{
partial class TimeZoneInfo
{
TimeSpan baseUtcOffset;
public TimeSpan BaseUtcOffset {
get { return baseUtcOffset; }
}
string daylightDisplayName;
public string DaylightName {
get {
return supportsDaylightSavingTime
? daylightDisplayName
: string.Empty;
}
}
string displayName;
public string DisplayName {
get { return displayName; }
}
string id;
public string Id {
get { return id; }
}
static TimeZoneInfo local;
public static TimeZoneInfo Local {
get {
var l = local;
if (l == null) {
l = CreateLocal ();
if (l == null)
throw new TimeZoneNotFoundException ();
if (Interlocked.CompareExchange (ref local, l, null) != null)
l = local;
}
return l;
}
}
/*
TimeZone transitions are stored when there is a change on the base offset.
*/
private List<KeyValuePair<DateTime, TimeType>> transitions;
private static bool readlinkNotFound;
[DllImport ("libc")]
private static extern int readlink (string path, byte[] buffer, int buflen);
private static string readlink (string path)
{
if (readlinkNotFound)
return null;
byte[] buf = new byte [512];
int ret;
try {
ret = readlink (path, buf, buf.Length);
} catch (DllNotFoundException) {
readlinkNotFound = true;
return null;
} catch (EntryPointNotFoundException) {
readlinkNotFound = true;
return null;
}
if (ret == -1) return null;
char[] cbuf = new char [512];
int chars = System.Text.Encoding.Default.GetChars (buf, 0, ret, cbuf, 0);
return new String (cbuf, 0, chars);
}
private static bool TryGetNameFromPath (string path, out string name)
{
name = null;
var linkPath = readlink (path);
if (linkPath != null) {
if (Path.IsPathRooted(linkPath))
path = linkPath;
else
path = Path.Combine(Path.GetDirectoryName(path), linkPath);
}
path = Path.GetFullPath (path);
if (string.IsNullOrEmpty (TimeZoneDirectory))
return false;
var baseDir = TimeZoneDirectory;
if (baseDir [baseDir.Length-1] != Path.DirectorySeparatorChar)
baseDir += Path.DirectorySeparatorChar;
if (!path.StartsWith (baseDir, StringComparison.InvariantCulture))
return false;
name = path.Substring (baseDir.Length);
if (name == "localtime")
name = "Local";
return true;
}
#if (!MONODROID && !MONOTOUCH && !XAMMAC && !WASM) || MOBILE_DESKTOP_HOST
static TimeZoneInfo CreateLocal ()
{
#if WIN_PLATFORM
if (IsWindows && LocalZoneKey != null) {
string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
if (name == null)
name = (string)LocalZoneKey.GetValue ("StandardName"); // windows xp
name = TrimSpecial (name);
if (name != null)
return TimeZoneInfo.FindSystemTimeZoneById (name);
} else if (IsWindows) {
return GetLocalTimeZoneInfoWinRTFallback ();
}
#endif
var tz = Environment.GetEnvironmentVariable ("TZ");
if (tz != null) {
if (tz == String.Empty)
return Utc;
try {
return FindSystemTimeZoneByFileName (tz, Path.Combine (TimeZoneDirectory, tz));
} catch {
return Utc;
}
}
var tzFilePaths = new string [] {
"/etc/localtime",
Path.Combine (TimeZoneDirectory, "localtime")};
foreach (var tzFilePath in tzFilePaths) {
try {
string tzName = null;
if (!TryGetNameFromPath (tzFilePath, out tzName))
tzName = "Local";
return FindSystemTimeZoneByFileName (tzName, tzFilePath);
} catch (TimeZoneNotFoundException) {
continue;
}
}
return Utc;
}
static TimeZoneInfo FindSystemTimeZoneByIdCore (string id)
{
#if LIBC
string filepath = Path.Combine (TimeZoneDirectory, id);
return FindSystemTimeZoneByFileName (id, filepath);
#else
throw new NotImplementedException ();
#endif
}
static void GetSystemTimeZonesCore (List<TimeZoneInfo> systemTimeZones)
{
#if WIN_PLATFORM
if (TimeZoneKey != null) {
foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
using (RegistryKey subkey = TimeZoneKey.OpenSubKey (id))
{
if (subkey == null || subkey.GetValue ("TZI") == null)
continue;
}
systemTimeZones.Add (FindSystemTimeZoneById (id));
}
return;
} else if (IsWindows) {
systemTimeZones.AddRange (GetSystemTimeZonesWinRTFallback ());
return;
}
#endif
#if LIBC
string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Australia", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
foreach (string continent in continents) {
try {
foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
try {
string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
systemTimeZones.Add (FindSystemTimeZoneById (id));
} catch (ArgumentNullException) {
} catch (TimeZoneNotFoundException) {
} catch (InvalidTimeZoneException) {
} catch (Exception) {
throw;
}
}
} catch {}
}
#else
throw new NotImplementedException ("This method is not implemented for this platform");
#endif
}
#endif // !MONODROID && !MONOTOUCH && !XAMMAC && !WASM
string standardDisplayName;
public string StandardName {
get { return standardDisplayName; }
}
bool supportsDaylightSavingTime;
public bool SupportsDaylightSavingTime {
get { return supportsDaylightSavingTime; }
}
static TimeZoneInfo utc;
public static TimeZoneInfo Utc {
get {
if (utc == null)
utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
return utc;
}
}
#if LIBC
const string DefaultTimeZoneDirectory = "/usr/share/zoneinfo";
static string timeZoneDirectory;
static string TimeZoneDirectory {
get {
if (timeZoneDirectory == null)
timeZoneDirectory = readlink (DefaultTimeZoneDirectory) ?? DefaultTimeZoneDirectory;
return timeZoneDirectory;
}
set {
ClearCachedData ();
timeZoneDirectory = value;
}
}
#endif
private AdjustmentRule [] adjustmentRules;
#if (!MOBILE || !FULL_AOT_DESKTOP || WIN_PLATFORM) && !XAMMAC_4_5
/// <summary>
/// Determine whether windows of not (taken Stephane Delcroix's code)
/// </summary>
private static bool IsWindows
{
get {
int platform = (int) Environment.OSVersion.Platform;
return ((platform != 4) && (platform != 6) && (platform != 128));
}
}
/// <summary>
/// Needed to trim misc garbage in MS registry keys
/// </summary>
private static string TrimSpecial (string str)
{
if (str == null)
return str;
var Istart = 0;
while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
var Iend = str.Length - 1;
while (Iend > Istart && !char.IsLetterOrDigit(str[Iend]) && str[Iend] != ')') // zone name can include parentheses like "Central Standard Time (Mexico)"
Iend--;
return str.Substring (Istart, Iend-Istart+1);
}
#if !FULL_AOT_DESKTOP || WIN_PLATFORM
static RegistryKey timeZoneKey;
static RegistryKey TimeZoneKey {
get {
if (timeZoneKey != null)
return timeZoneKey;
if (!IsWindows)
return null;
try {
return timeZoneKey = Registry.LocalMachine.OpenSubKey (
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
false);
} catch {
return null;
}
}
}
static RegistryKey localZoneKey;
static RegistryKey LocalZoneKey {
get {
if (localZoneKey != null)
return localZoneKey;
if (!IsWindows)
return null;
try {
return localZoneKey = Registry.LocalMachine.OpenSubKey (
"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
} catch {
return null;
}
}
}
#endif
#endif // !MOBILE || !FULL_AOT_DESKTOP || WIN_PLATFORM
private static bool TryAddTicks (DateTime date, long ticks, out DateTime result, DateTimeKind kind = DateTimeKind.Unspecified)
{
var resultTicks = date.Ticks + ticks;
if (resultTicks < DateTime.MinValue.Ticks) {
result = DateTime.SpecifyKind (DateTime.MinValue, kind);
return false;
}
if (resultTicks > DateTime.MaxValue.Ticks) {
result = DateTime.SpecifyKind (DateTime.MaxValue, kind);
return false;
}
result = new DateTime (resultTicks, kind);
return true;
}
public static void ClearCachedData ()
{
local = null;
utc = null;
systemTimeZones = null;
}
public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
{
return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
}
public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
{
if (sourceTimeZone == null)
throw new ArgumentNullException ("sourceTimeZone");
if (destinationTimeZone == null)
throw new ArgumentNullException ("destinationTimeZone");
if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
if (sourceTimeZone.IsInvalidTime (dateTime))
throw new ArgumentException ("dateTime parameter is an invalid time");
if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
return dateTime;
DateTime utc = ConvertTimeToUtc (dateTime, sourceTimeZone);
if (destinationTimeZone != TimeZoneInfo.Utc) {
utc = ConvertTimeFromUtc (utc, destinationTimeZone);
if (dateTime.Kind == DateTimeKind.Unspecified)
return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
}
return utc;
}
public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
{
if (destinationTimeZone == null)
throw new ArgumentNullException("destinationTimeZone");
var utcDateTime = dateTimeOffset.UtcDateTime;
bool isDst;
var utcOffset = destinationTimeZone.GetUtcOffset(utcDateTime, out isDst);
return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + utcOffset, utcOffset);
}
public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
{
return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
}
public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
{
TimeZoneInfo source_tz;
if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZoneId == TimeZoneInfo.Utc.Id) {
source_tz = Utc;
} else {
source_tz = FindSystemTimeZoneById (sourceTimeZoneId);
}
return ConvertTime (dateTime, source_tz, FindSystemTimeZoneById (destinationTimeZoneId));
}
public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
{
return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
}
private DateTime ConvertTimeFromUtc (DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local)
throw new ArgumentException ("Kind property of dateTime is Local");
if (this == TimeZoneInfo.Utc)
return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
var utcOffset = GetUtcOffset (dateTime);
var kind = (this == TimeZoneInfo.Local)? DateTimeKind.Local : DateTimeKind.Unspecified;
DateTime result;
if (!TryAddTicks (dateTime, utcOffset.Ticks, out result, kind))
return DateTime.SpecifyKind (DateTime.MaxValue, kind);
return result;
}
public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
{
if (destinationTimeZone == null)
throw new ArgumentNullException ("destinationTimeZone");
return destinationTimeZone.ConvertTimeFromUtc (dateTime);
}
public static DateTime ConvertTimeToUtc (DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime;
return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local);
}
static internal DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
{
return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local, flags);
}
public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
{
return ConvertTimeToUtc (dateTime, sourceTimeZone, TimeZoneInfoOptions.None);
}
static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfoOptions flags)
{
if ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) {
if (sourceTimeZone == null)
throw new ArgumentNullException ("sourceTimeZone");
if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
if (sourceTimeZone.IsInvalidTime (dateTime))
throw new ArgumentException ("dateTime parameter is an invalid time");
}
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime;
bool isDst;
var utcOffset = sourceTimeZone.GetUtcOffset (dateTime, out isDst);
DateTime utcDateTime;
TryAddTicks (dateTime, -utcOffset.Ticks, out utcDateTime, DateTimeKind.Utc);
return utcDateTime;
}
static internal TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out Boolean isAmbiguousLocalDst)
{
bool isDaylightSavings;
return GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst);
}
public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
{
return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
}
public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
{
return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
}
public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
{
return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
}
public override bool Equals (object obj)
{
return Equals (obj as TimeZoneInfo);
}
public bool Equals (TimeZoneInfo other)
{
if (other == null)
return false;
return other.Id == this.Id && HasSameRules (other);
}
public static TimeZoneInfo FindSystemTimeZoneById (string id)
{
//FIXME: this method should check for cached values in systemTimeZones
if (id == null)
throw new ArgumentNullException ("id");
#if WIN_PLATFORM
if (TimeZoneKey != null)
{
if (id == "Coordinated Universal Time")
id = "UTC"; //windows xp exception for "StandardName" property
RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
if (key == null)
throw new TimeZoneNotFoundException ();
return FromRegistryKey(id, key);
} else if (IsWindows) {
return FindSystemTimeZoneByIdWinRTFallback (id);
}
#endif
// Local requires special logic that already exists in the Local property (bug #326)
if (id == "Local")
return Local;
return FindSystemTimeZoneByIdCore (id);
}
#if LIBC
private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
{
FileStream stream = null;
try {
stream = File.OpenRead (filepath);
} catch (Exception ex) {
throw new TimeZoneNotFoundException ("Couldn't read time zone file " + filepath, ex);
}
try {
return BuildFromStream (id, stream);
} finally {
if (stream != null)
stream.Dispose();
}
}
#endif
#if WIN_PLATFORM
private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
{
byte [] reg_tzi = (byte []) key.GetValue ("TZI");
if (reg_tzi == null)
throw new InvalidTimeZoneException ();
int bias = BitConverter.ToInt32 (reg_tzi, 0);
TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
string display_name = (string) key.GetValue ("Display");
string standard_name = (string) key.GetValue ("Std");
string daylight_name = (string) key.GetValue ("Dlt");
List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
if (dst_key != null) {
int first_year = (int) dst_key.GetValue ("FirstEntry");
int last_year = (int) dst_key.GetValue ("LastEntry");
int year;
for (year=first_year; year<=last_year; year++) {
byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
if (dst_tzi != null) {
int start_year = year == first_year ? 1 : year;
int end_year = year == last_year ? 9999 : year;
ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
}
}
}
else
ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules));
}
private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
{
//int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
int daylight_bias = BitConverter.ToInt32 (buffer, 8);
int standard_year = BitConverter.ToInt16 (buffer, 12);
int standard_month = BitConverter.ToInt16 (buffer, 14);
int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
int standard_day = BitConverter.ToInt16 (buffer, 18);
int standard_hour = BitConverter.ToInt16 (buffer, 20);
int standard_minute = BitConverter.ToInt16 (buffer, 22);
int standard_second = BitConverter.ToInt16 (buffer, 24);
int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
int daylight_year = BitConverter.ToInt16 (buffer, 28);
int daylight_month = BitConverter.ToInt16 (buffer, 30);
int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
int daylight_day = BitConverter.ToInt16 (buffer, 34);
int daylight_hour = BitConverter.ToInt16 (buffer, 36);
int daylight_minute = BitConverter.ToInt16 (buffer, 38);
int daylight_second = BitConverter.ToInt16 (buffer, 40);
int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
if (standard_month == 0 || daylight_month == 0)
return;
DateTime start_date;
DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
TransitionTime start_transition_time;
start_date = new DateTime (start_year, 1, 1);
if (daylight_year == 0) {
start_transition_time = TransitionTime.CreateFloatingDateRule (
start_timeofday, daylight_month, daylight_day,
(DayOfWeek) daylight_dayofweek);
}
else {
start_transition_time = TransitionTime.CreateFixedDateRule (
start_timeofday, daylight_month, daylight_day);
}
DateTime end_date;
DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
TransitionTime end_transition_time;
end_date = new DateTime (end_year, 12, 31);
if (standard_year == 0) {
end_transition_time = TransitionTime.CreateFloatingDateRule (
end_timeofday, standard_month, standard_day,
(DayOfWeek) standard_dayofweek);
}
else {
end_transition_time = TransitionTime.CreateFixedDateRule (
end_timeofday, standard_month, standard_day);
}
TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
start_date, end_date, daylight_delta,
start_transition_time, end_transition_time));
}
#endif
public AdjustmentRule [] GetAdjustmentRules ()
{
if (!supportsDaylightSavingTime || adjustmentRules == null)
return new AdjustmentRule [0];
else
return (AdjustmentRule []) adjustmentRules.Clone ();
}
public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
{
if (!IsAmbiguousTime (dateTime))
throw new ArgumentException ("dateTime is not an ambiguous time");
AdjustmentRule rule = GetApplicableRule (dateTime);
if (rule != null)
return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
else
return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
}
public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
{
if (!IsAmbiguousTime (dateTimeOffset))
throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
throw new NotImplementedException ();
}
public override int GetHashCode ()
{
int hash_code = Id.GetHashCode ();
foreach (AdjustmentRule rule in GetAdjustmentRules ())
hash_code ^= rule.GetHashCode ();
return hash_code;
}
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException ("info");
info.AddValue ("Id", id);
info.AddValue ("DisplayName", displayName);
info.AddValue ("StandardName", standardDisplayName);
info.AddValue ("DaylightName", daylightDisplayName);
info.AddValue ("BaseUtcOffset", baseUtcOffset);
info.AddValue ("AdjustmentRules", adjustmentRules);
info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
}
static ReadOnlyCollection<TimeZoneInfo> systemTimeZones;
public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
{
if (systemTimeZones == null) {
var tz = new List<TimeZoneInfo> ();
GetSystemTimeZonesCore (tz);
Interlocked.CompareExchange (ref systemTimeZones, new ReadOnlyCollection<TimeZoneInfo> (tz), null);
}
return systemTimeZones;
}
public TimeSpan GetUtcOffset (DateTime dateTime)
{
bool isDST;
return GetUtcOffset (dateTime, out isDST);
}
public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
{
bool isDST;
return GetUtcOffset (dateTimeOffset.UtcDateTime, out isDST);
}
private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST, bool forOffset = false)
{
isDST = false;
TimeZoneInfo tz = this;
if (dateTime.Kind == DateTimeKind.Utc)
tz = TimeZoneInfo.Utc;
if (dateTime.Kind == DateTimeKind.Local)
tz = TimeZoneInfo.Local;
bool isTzDst;
var tzOffset = GetUtcOffsetHelper (dateTime, tz, out isTzDst, forOffset);
if (tz == this) {
isDST = isTzDst;
return tzOffset;
}
DateTime utcDateTime;
if (!TryAddTicks (dateTime, -tzOffset.Ticks, out utcDateTime, DateTimeKind.Utc))
return BaseUtcOffset;
return GetUtcOffsetHelper (utcDateTime, this, out isDST, forOffset);
}
// This is an helper method used by the method above, do not use this on its own.
private static TimeSpan GetUtcOffsetHelper (DateTime dateTime, TimeZoneInfo tz, out bool isDST, bool forOffset = false)
{
if (dateTime.Kind == DateTimeKind.Local && tz != TimeZoneInfo.Local)
throw new Exception ();
isDST = false;
if (tz == TimeZoneInfo.Utc)
return TimeSpan.Zero;
TimeSpan offset;
if (tz.TryGetTransitionOffset(dateTime, out offset, out isDST, forOffset))
return offset;
if (dateTime.Kind == DateTimeKind.Utc) {
var utcRule = tz.GetApplicableRule (dateTime);
if (utcRule != null && tz.IsInDST (utcRule, dateTime)) {
isDST = true;
return tz.BaseUtcOffset + utcRule.DaylightDelta;
}
return tz.BaseUtcOffset;
}
DateTime stdUtcDateTime;
if (!TryAddTicks (dateTime, -tz.BaseUtcOffset.Ticks, out stdUtcDateTime, DateTimeKind.Utc))
return tz.BaseUtcOffset;
var tzRule = tz.GetApplicableRule (stdUtcDateTime);
DateTime dstUtcDateTime = DateTime.MinValue;
if (tzRule != null) {
if (!TryAddTicks (stdUtcDateTime, -tzRule.DaylightDelta.Ticks, out dstUtcDateTime, DateTimeKind.Utc))
return tz.BaseUtcOffset;
}
if (tzRule != null && tz.IsInDST (tzRule, dateTime)) {
// Replicate what .NET does when given a time which falls into the hour which is lost when
// DST starts. isDST should be false and the offset should be BaseUtcOffset without the
// DST delta while in that hour.
if (forOffset)
isDST = true;
if (tz.IsInDST (tzRule, dstUtcDateTime)) {
isDST = true;
return tz.BaseUtcOffset + tzRule.DaylightDelta;
} else {
return tz.BaseUtcOffset;
}
}
return tz.BaseUtcOffset;
}
public bool HasSameRules (TimeZoneInfo other)
{
if (other == null)
throw new ArgumentNullException ("other");
if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
return false;
if (this.adjustmentRules == null)
return true;
if (this.BaseUtcOffset != other.BaseUtcOffset)
return false;
if (this.adjustmentRules.Length != other.adjustmentRules.Length)
return false;
for (int i = 0; i < adjustmentRules.Length; i++) {
if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
return false;
}
return true;
}
public bool IsAmbiguousTime (DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
throw new ArgumentException ("Kind is Local and time is Invalid");
if (this == TimeZoneInfo.Utc)
return false;
if (dateTime.Kind == DateTimeKind.Utc)
dateTime = ConvertTimeFromUtc (dateTime);
if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
AdjustmentRule rule = GetApplicableRule (dateTime);
if (rule != null) {
DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
return true;
}
return false;
}
public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
{
throw new NotImplementedException ();
}
private bool IsInDST (AdjustmentRule rule, DateTime dateTime)
{
// Check whether we're in the dateTime year's DST period
if (IsInDSTForYear (rule, dateTime, dateTime.Year))
return true;
// We might be in the dateTime previous year's DST period
return dateTime.Year > 1 && IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
}
bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
{
DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
if (dateTime.Kind == DateTimeKind.Utc) {
DST_start -= BaseUtcOffset;
DST_end -= (BaseUtcOffset + rule.DaylightDelta);
}
return (dateTime >= DST_start && dateTime < DST_end);
}
public bool IsDaylightSavingTime (DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
throw new ArgumentException ("dateTime is invalid and Kind is Local");
if (this == TimeZoneInfo.Utc)
return false;
if (!SupportsDaylightSavingTime)
return false;
bool isDst;
GetUtcOffset (dateTime, out isDst);
return isDst;
}
internal bool IsDaylightSavingTime (DateTime dateTime, TimeZoneInfoOptions flags)
{
return IsDaylightSavingTime (dateTime);
}
public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
{
var dateTime = dateTimeOffset.DateTime;
if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
throw new ArgumentException ("dateTime is invalid and Kind is Local");
if (this == TimeZoneInfo.Utc)
return false;
if (!SupportsDaylightSavingTime)
return false;
bool isDst;
GetUtcOffset (dateTime, out isDst, true);
return isDst;
}
internal DaylightTime GetDaylightChanges (int year)
{
DateTime start = DateTime.MinValue, end = DateTime.MinValue;
TimeSpan delta = new TimeSpan ();
if (transitions != null) {
end = DateTime.MaxValue;
for (var i = transitions.Count - 1; i >= 0; i--) {
var pair = transitions [i];
DateTime ttime = pair.Key;
TimeType ttype = pair.Value;
if (ttime.Year > year)
continue;
if (ttime.Year < year)
break;
if (ttype.IsDst) {
// DaylightTime.Delta is relative to the current BaseUtcOffset.
delta = new TimeSpan (0, 0, ttype.Offset) - BaseUtcOffset;
start = ttime;
} else {
end = ttime;
}
}
// DaylightTime.Start is relative to the Standard time.
if (!TryAddTicks (start, BaseUtcOffset.Ticks, out start))
start = DateTime.MinValue;
// DaylightTime.End is relative to the DST time.
if (!TryAddTicks (end, BaseUtcOffset.Ticks + delta.Ticks, out end))
end = DateTime.MinValue;