-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
TimeZoneInfo.Unix.cs
1356 lines (1187 loc) · 63 KB
/
TimeZoneInfo.Unix.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.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Security;
using Microsoft.Win32.SafeHandles;
namespace System
{
public sealed partial class TimeZoneInfo
{
private const string DefaultTimeZoneDirectory = "/usr/share/zoneinfo/";
// UTC aliases per https://github.com/unicode-org/cldr/blob/master/common/bcp47/timezone.xml
// Hard-coded because we need to treat all aliases of UTC the same even when globalization data is not available.
// (This list is not likely to change.)
private static readonly string[] s_UtcAliases = new[] {
"Etc/UTC",
"Etc/UCT",
"Etc/Universal",
"Etc/Zulu",
"UCT",
"UTC",
"Universal",
"Zulu"
};
private TimeZoneInfo(byte[] data, string id, bool dstDisabled)
{
_id = id;
HasIanaId = true;
// Handle UTC and its aliases
if (StringArrayContains(_id, s_UtcAliases, StringComparison.OrdinalIgnoreCase))
{
_standardDisplayName = GetUtcStandardDisplayName();
_daylightDisplayName = _standardDisplayName;
_displayName = GetUtcFullDisplayName(_id, _standardDisplayName);
_baseUtcOffset = TimeSpan.Zero;
_adjustmentRules = Array.Empty<AdjustmentRule>();
return;
}
TZifHead t;
DateTime[] dts;
byte[] typeOfLocalTime;
TZifType[] transitionType;
string zoneAbbreviations;
string? futureTransitionsPosixFormat;
string? standardAbbrevName = null;
string? daylightAbbrevName = null;
// parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed.
TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out futureTransitionsPosixFormat);
// find the best matching baseUtcOffset and display strings based on the current utcNow value.
// NOTE: read the Standard and Daylight display strings from the tzfile now in case they can't be loaded later
// from the globalization data.
DateTime utcNow = DateTime.UtcNow;
for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++)
{
int type = typeOfLocalTime[i];
if (!transitionType[type].IsDst)
{
_baseUtcOffset = transitionType[type].UtcOffset;
standardAbbrevName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
}
else
{
daylightAbbrevName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
}
}
if (dts.Length == 0)
{
// time zones like Africa/Bujumbura and Etc/GMT* have no transition times but still contain
// TZifType entries that may contain a baseUtcOffset and display strings
for (int i = 0; i < transitionType.Length; i++)
{
if (!transitionType[i].IsDst)
{
_baseUtcOffset = transitionType[i].UtcOffset;
standardAbbrevName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
}
else
{
daylightAbbrevName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
}
}
}
// Set fallback values using abbreviations, base offset, and id
// These are expected in environments without time zone globalization data
_standardDisplayName = standardAbbrevName;
_daylightDisplayName = daylightAbbrevName ?? standardAbbrevName;
_displayName = string.Create(null, stackalloc char[256], $"(UTC{(_baseUtcOffset >= TimeSpan.Zero ? '+' : '-')}{_baseUtcOffset:hh\\:mm}) {_id}");
// Try to populate the display names from the globalization data
TryPopulateTimeZoneDisplayNamesFromGlobalizationData(_id, _baseUtcOffset, ref _standardDisplayName, ref _daylightDisplayName, ref _displayName);
// TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
// with DateTimeOffset, SQL Server, and the W3C XML Specification
if (_baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
{
_baseUtcOffset = new TimeSpan(_baseUtcOffset.Hours, _baseUtcOffset.Minutes, 0);
}
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
TZif_GenerateAdjustmentRules(out _adjustmentRules, _baseUtcOffset, dts, typeOfLocalTime, transitionType, futureTransitionsPosixFormat);
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
}
// The TransitionTime fields are not used when AdjustmentRule.NoDaylightTransitions == true.
// However, there are some cases in the past where DST = true, and the daylight savings offset
// now equals what the current BaseUtcOffset is. In that case, the AdjustmentRule.DaylightOffset
// is going to be TimeSpan.Zero. But we still need to return 'true' from AdjustmentRule.HasDaylightSaving.
// To ensure we always return true from HasDaylightSaving, make a "special" dstStart that will make the logic
// in HasDaylightSaving return true.
private static readonly TransitionTime s_daylightRuleMarker = TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(2), 1, 1);
// Truncate the date and the time to Milliseconds precision
private static DateTime GetTimeOnlyInMillisecondsPrecision(DateTime input) => new DateTime((input.TimeOfDay.Ticks / TimeSpan.TicksPerMillisecond) * TimeSpan.TicksPerMillisecond);
/// <summary>
/// Returns a cloned array of AdjustmentRule objects
/// </summary>
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
// The rules we use in Unix care mostly about the start and end dates but don't fill the transition start and end info.
// as the rules now is public, we should fill it properly so the caller doesn't have to know how we use it internally
// and can use it as it is used in Windows
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(_adjustmentRules.Length);
for (int i = 0; i < _adjustmentRules.Length; i++)
{
AdjustmentRule rule = _adjustmentRules[i];
if (rule.NoDaylightTransitions &&
rule.DaylightTransitionStart != s_daylightRuleMarker &&
rule.DaylightDelta == TimeSpan.Zero && rule.BaseUtcOffsetDelta == TimeSpan.Zero)
{
// This rule has no time transition, ignore it.
continue;
}
DateTime start = rule.DateStart.Kind == DateTimeKind.Utc ?
// At the daylight start we didn't start the daylight saving yet then we convert to Local time
// by adding the _baseUtcOffset to the UTC time
new DateTime(rule.DateStart.Ticks + _baseUtcOffset.Ticks, DateTimeKind.Unspecified) :
rule.DateStart;
DateTime end = rule.DateEnd.Kind == DateTimeKind.Utc ?
// At the daylight saving end, the UTC time is mapped to local time which is already shifted by the daylight delta
// we calculate the local time by adding _baseUtcOffset + DaylightDelta to the UTC time
new DateTime(rule.DateEnd.Ticks + _baseUtcOffset.Ticks + rule.DaylightDelta.Ticks, DateTimeKind.Unspecified) :
rule.DateEnd;
if (start.Year == end.Year || !rule.NoDaylightTransitions)
{
// If the rule is covering only one year then the start and end transitions would occur in that year, we don't need to split the rule.
// Also, rule.NoDaylightTransitions be false in case the rule was created from a POSIX time zone string and having a DST transition. We can represent this in one rule too
TransitionTime startTransition = rule.NoDaylightTransitions ? TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(start), start.Month, start.Day) : rule.DaylightTransitionStart;
TransitionTime endTransition = rule.NoDaylightTransitions ? TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(end), end.Month, end.Day) : rule.DaylightTransitionEnd;
rulesList.Add(AdjustmentRule.CreateAdjustmentRule(start.Date, end.Date, rule.DaylightDelta, startTransition, endTransition, rule.BaseUtcOffsetDelta));
}
else
{
// For rules spanning more than one year. The time transition inside this rule would apply for the whole time spanning these years
// and not for partial time of every year.
// AdjustmentRule cannot express such rule using the DaylightTransitionStart and DaylightTransitionEnd because
// the DaylightTransitionStart and DaylightTransitionEnd express the transition for every year.
// We split the rule into more rules. The first rule will start from the start year of the original rule and ends at the end of the same year.
// The second splitted rule would cover the middle range of the original rule and ranging from the year start+1 to
// year end-1. The transition time in this rule would start from Jan 1st to end of December.
// The last splitted rule would start from the Jan 1st of the end year of the original rule and ends at the end transition time of the original rule.
// Add the first rule.
DateTime endForFirstRule = new DateTime(start.Year + 1, 1, 1).AddMilliseconds(-1); // At the end of the first year
TransitionTime startTransition = TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(start), start.Month, start.Day);
TransitionTime endTransition = TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(endForFirstRule), endForFirstRule.Month, endForFirstRule.Day);
rulesList.Add(AdjustmentRule.CreateAdjustmentRule(start.Date, endForFirstRule.Date, rule.DaylightDelta, startTransition, endTransition, rule.BaseUtcOffsetDelta));
// Check if there is range of years between the start and the end years
if (end.Year - start.Year > 1)
{
// Add the middle rule.
DateTime middleYearStart = new DateTime(start.Year + 1, 1, 1);
DateTime middleYearEnd = new DateTime(end.Year, 1, 1).AddMilliseconds(-1);
startTransition = TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(middleYearStart), middleYearStart.Month, middleYearStart.Day);
endTransition = TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(middleYearEnd), middleYearEnd.Month, middleYearEnd.Day);
rulesList.Add(AdjustmentRule.CreateAdjustmentRule(middleYearStart.Date, middleYearEnd.Date, rule.DaylightDelta, startTransition, endTransition, rule.BaseUtcOffsetDelta));
}
// Add the end rule.
DateTime endYearStart = new DateTime(end.Year, 1, 1); // At the beginning of the last year
startTransition = TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(endYearStart), endYearStart.Month, endYearStart.Day);
endTransition = TransitionTime.CreateFixedDateRule(GetTimeOnlyInMillisecondsPrecision(end), end.Month, end.Day);
rulesList.Add(AdjustmentRule.CreateAdjustmentRule(endYearStart.Date, end.Date, rule.DaylightDelta, startTransition, endTransition, rule.BaseUtcOffsetDelta));
}
}
return rulesList.ToArray();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
foreach (string timeZoneId in GetTimeZoneIds())
{
TryGetTimeZone(timeZoneId, false, out _, out _, cachedData, alwaysFallbackToLocalMachine: true); // populate the cache
}
}
/// <summary>
/// Helper function for retrieving the local system time zone.
/// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
/// Assumes cachedData lock is taken.
/// </summary>
/// <returns>A new TimeZoneInfo instance.</returns>
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
return GetLocalTimeZoneCore();
}
private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo? value, out Exception? e)
{
return TryGetTimeZoneFromLocalMachineCore(id, out value, out e);
}
private static TimeZoneInfo? GetTimeZoneFromTzData(byte[]? rawData, string id)
{
if (rawData != null)
{
try
{
return new TimeZoneInfo(rawData, id, dstDisabled: false); // create a TimeZoneInfo instance from the TZif data w/ DST support
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
try
{
return new TimeZoneInfo(rawData, id, dstDisabled: true); // create a TimeZoneInfo instance from the TZif data w/o DST support
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
return null;
}
/// <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 a valid TimeZoneInfo instance or
/// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
/// </summary>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// 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))
{
return Utc;
}
ArgumentNullException.ThrowIfNull(id);
if (id.Length == 0 || id.Contains('\0'))
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo? value;
Exception? e;
TimeZoneInfoResult result;
CachedData cachedData = s_cachedData;
lock (cachedData)
{
result = TryGetTimeZone(id, false, out value, out e, cachedData, alwaysFallbackToLocalMachine: true);
}
if (result == TimeZoneInfoResult.Success)
{
return value!;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
Debug.Assert(e is InvalidTimeZoneException,
"TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
throw e;
}
else if (result == TimeZoneInfoResult.SecurityException)
{
throw new SecurityException(SR.Format(SR.Security_CannotReadFileData, id), e);
}
else
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
// DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
{
// Use the standard code path for Unix since there isn't a faster way of handling current-year-only time zones
return GetUtcOffsetFromUtc(time, Local, out _, out isAmbiguousLocalDst);
}
// TZFILE(5) BSD File Formats Manual TZFILE(5)
//
// NAME
// tzfile -- timezone information
//
// SYNOPSIS
// #include "/usr/src/lib/libc/stdtime/tzfile.h"
//
// DESCRIPTION
// The time zone information files used by tzset(3) begin with the magic
// characters ``TZif'' to identify them as time zone information files, fol-
// lowed by sixteen bytes reserved for future use, followed by four four-
// byte values written in a ``standard'' byte order (the high-order byte of
// the value is written first). These values are, in order:
//
// tzh_ttisgmtcnt The number of UTC/local indicators stored in the file.
// tzh_ttisstdcnt The number of standard/wall indicators stored in the
// file.
// tzh_leapcnt The number of leap seconds for which data is stored in
// the file.
// tzh_timecnt The number of ``transition times'' for which data is
// stored in the file.
// tzh_typecnt The number of ``local time types'' for which data is
// stored in the file (must not be zero).
// tzh_charcnt The number of characters of ``time zone abbreviation
// strings'' stored in the file.
//
// The above header is followed by tzh_timecnt four-byte values of type
// long, sorted in ascending order. These values are written in ``stan-
// dard'' byte order. Each is used as a transition time (as returned by
// time(3)) at which the rules for computing local time change. Next come
// tzh_timecnt one-byte values of type unsigned char; each one tells which
// of the different types of ``local time'' types described in the file is
// associated with the same-indexed transition time. These values serve as
// indices into an array of ttinfo structures that appears next in the file;
// these structures are defined as follows:
//
// struct ttinfo {
// long tt_gmtoff;
// int tt_isdst;
// unsigned int tt_abbrind;
// };
//
// Each structure is written as a four-byte value for tt_gmtoff of type
// long, in a standard byte order, followed by a one-byte value for tt_isdst
// and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives
// the number of seconds to be added to UTC, tt_isdst tells whether tm_isdst
// should be set by localtime(3) and tt_abbrind serves as an index into the
// array of time zone abbreviation characters that follow the ttinfo struc-
// ture(s) in the file.
//
// Then there are tzh_leapcnt pairs of four-byte values, written in standard
// byte order; the first value of each pair gives the time (as returned by
// time(3)) at which a leap second occurs; the second gives the total number
// of leap seconds to be applied after the given time. The pairs of values
// are sorted in ascending order by time.b
//
// Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a
// one-byte value; they tell whether the transition times associated with
// local time types were specified as standard time or wall clock time, and
// are used when a time zone file is used in handling POSIX-style time zone
// environment variables.
//
// Finally there are tzh_ttisgmtcnt UTC/local indicators, each stored as a
// one-byte value; they tell whether the transition times associated with
// local time types were specified as UTC or local time, and are used when a
// time zone file is used in handling POSIX-style time zone environment
// variables.
//
// localtime uses the first standard-time ttinfo structure in the file (or
// simply the first ttinfo structure in the absence of a standard-time
// structure) if either tzh_timecnt is zero or the time argument is less
// than the first transition time recorded in the file.
//
// SEE ALSO
// ctime(3), time2posix(3), zic(8)
//
// BSD September 13, 1994 BSD
//
//
//
// TIME(3) BSD Library Functions Manual TIME(3)
//
// NAME
// time -- get time of day
//
// LIBRARY
// Standard C Library (libc, -lc)
//
// SYNOPSIS
// #include <time.h>
//
// time_t
// time(time_t *tloc);
//
// DESCRIPTION
// The time() function returns the value of time in seconds since 0 hours, 0
// minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without
// including leap seconds. If an error occurs, time() returns the value
// (time_t)-1.
//
// The return value is also stored in *tloc, provided that tloc is non-null.
//
// ERRORS
// The time() function may fail for any of the reasons described in
// gettimeofday(2).
//
// SEE ALSO
// gettimeofday(2), ctime(3)
//
// STANDARDS
// The time function conforms to IEEE Std 1003.1-2001 (``POSIX.1'').
//
// BUGS
// Neither ISO/IEC 9899:1999 (``ISO C99'') nor IEEE Std 1003.1-2001
// (``POSIX.1'') requires time() to set errno on failure; thus, it is impos-
// sible for an application to distinguish the valid time value -1 (repre-
// senting the last UTC second of 1969) from the error return value.
//
// Systems conforming to earlier versions of the C and POSIX standards
// (including older versions of FreeBSD) did not set *tloc in the error
// case.
//
// HISTORY
// A time() function appeared in Version 6 AT&T UNIX.
//
// BSD July 18, 2003 BSD
//
//
private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[]? rules, TimeSpan baseUtcOffset, DateTime[] dts, byte[] typeOfLocalTime,
TZifType[] transitionType, string? futureTransitionsPosixFormat)
{
rules = null;
if (dts.Length > 0)
{
int index = 0;
List<AdjustmentRule> rulesList = new List<AdjustmentRule>();
while (index <= dts.Length)
{
TZif_GenerateAdjustmentRule(ref index, baseUtcOffset, rulesList, dts, typeOfLocalTime, transitionType, futureTransitionsPosixFormat);
}
rules = rulesList.ToArray();
if (rules != null && rules.Length == 0)
{
rules = null;
}
}
}
private static void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZoneBaseUtcOffset, List<AdjustmentRule> rulesList, DateTime[] dts,
byte[] typeOfLocalTime, TZifType[] transitionTypes, string? futureTransitionsPosixFormat)
{
// To generate AdjustmentRules, use the following approach:
// The first AdjustmentRule will go from DateTime.MinValue to the first transition time greater than DateTime.MinValue.
// Each middle AdjustmentRule wil go from dts[index-1] to dts[index].
// The last AdjustmentRule will go from dts[dts.Length-1] to Datetime.MaxValue.
// 0. Skip any DateTime.MinValue transition times. In newer versions of the tzfile, there
// is a "big bang" transition time, which is before the year 0001. Since any times before year 0001
// cannot be represented by DateTime, there is no reason to make AdjustmentRules for these unrepresentable time periods.
// 1. If there are no DateTime.MinValue times, the first AdjustmentRule goes from DateTime.MinValue
// to the first transition and uses the first standard transitionType (or the first transitionType if none of them are standard)
// 2. Create an AdjustmentRule for each transition, i.e. from dts[index - 1] to dts[index].
// This rule uses the transitionType[index - 1] and the whole AdjustmentRule only describes a single offset - either
// all daylight savings, or all standard time.
// 3. After all the transitions are filled out, the last AdjustmentRule is created from either:
// a. a POSIX-style timezone description ("futureTransitionsPosixFormat"), if there is one or
// b. continue the last transition offset until DateTime.Max
while (index < dts.Length && dts[index] == DateTime.MinValue)
{
index++;
}
if (rulesList.Count == 0 && index < dts.Length)
{
TZifType transitionType = TZif_GetEarlyDateTransitionType(transitionTypes);
DateTime endTransitionDate = dts[index];
TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
DateTime.MinValue,
endTransitionDate.AddTicks(-1),
daylightDelta,
default,
default,
baseUtcDelta,
noDaylightTransitions: true);
if (!IsValidAdjustmentRuleOffset(timeZoneBaseUtcOffset, r))
{
NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
}
rulesList.Add(r);
}
else if (index < dts.Length)
{
DateTime startTransitionDate = dts[index - 1];
TZifType startTransitionType = transitionTypes[typeOfLocalTime[index - 1]];
DateTime endTransitionDate = dts[index];
TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(startTransitionType.UtcOffset, timeZoneBaseUtcOffset);
TimeSpan daylightDelta = startTransitionType.IsDst ? transitionOffset : TimeSpan.Zero;
TimeSpan baseUtcDelta = startTransitionType.IsDst ? TimeSpan.Zero : transitionOffset;
TransitionTime dstStart;
if (startTransitionType.IsDst)
{
// the TransitionTime fields are not used when AdjustmentRule.NoDaylightTransitions == true.
// However, there are some cases in the past where DST = true, and the daylight savings offset
// now equals what the current BaseUtcOffset is. In that case, the AdjustmentRule.DaylightOffset
// is going to be TimeSpan.Zero. But we still need to return 'true' from AdjustmentRule.HasDaylightSaving.
// To ensure we always return true from HasDaylightSaving, make a "special" dstStart that will make the logic
// in HasDaylightSaving return true.
dstStart = s_daylightRuleMarker;
}
else
{
dstStart = default;
}
AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
startTransitionDate,
endTransitionDate.AddTicks(-1),
daylightDelta,
dstStart,
default,
baseUtcDelta,
noDaylightTransitions: true);
if (!IsValidAdjustmentRuleOffset(timeZoneBaseUtcOffset, r))
{
NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
}
rulesList.Add(r);
}
else
{
// create the AdjustmentRule that will be used for all DateTimes after the last transition
// NOTE: index == dts.Length
DateTime startTransitionDate = dts[index - 1];
AdjustmentRule? r = !string.IsNullOrEmpty(futureTransitionsPosixFormat) ?
TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset) :
null;
if (r == null)
{
// just use the last transition as the rule which will be used until the end of time
TZifType transitionType = transitionTypes[typeOfLocalTime[index - 1]];
TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
r = AdjustmentRule.CreateAdjustmentRule(
startTransitionDate,
DateTime.MaxValue,
daylightDelta,
default,
default,
baseUtcDelta,
noDaylightTransitions: true);
}
if (!IsValidAdjustmentRuleOffset(timeZoneBaseUtcOffset, r))
{
NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
}
rulesList.Add(r);
}
index++;
}
private static TimeSpan TZif_CalculateTransitionOffsetFromBase(TimeSpan transitionOffset, TimeSpan timeZoneBaseUtcOffset)
{
TimeSpan result = transitionOffset - timeZoneBaseUtcOffset;
// TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
// with DateTimeOffset, SQL Server, and the W3C XML Specification
if (result.Ticks % TimeSpan.TicksPerMinute != 0)
{
result = new TimeSpan(result.Hours, result.Minutes, 0);
}
return result;
}
/// <summary>
/// Gets the first standard-time transition type, or simply the first transition type
/// if there are no standard transition types.
/// </summary>>
/// <remarks>
/// from 'man tzfile':
/// localtime(3) uses the first standard-time ttinfo structure in the file
/// (or simply the first ttinfo structure in the absence of a standard-time
/// structure) if either tzh_timecnt is zero or the time argument is less
/// than the first transition time recorded in the file.
/// </remarks>
private static TZifType TZif_GetEarlyDateTransitionType(TZifType[] transitionTypes)
{
foreach (TZifType transitionType in transitionTypes)
{
if (!transitionType.IsDst)
{
return transitionType;
}
}
if (transitionTypes.Length > 0)
{
return transitionTypes[0];
}
throw new InvalidTimeZoneException(SR.InvalidTimeZone_NoTTInfoStructures);
}
/// <summary>
/// Creates an AdjustmentRule given the POSIX TZ environment variable string.
/// </summary>
/// <remarks>
/// See http://man7.org/linux/man-pages/man3/tzset.3.html for the format and semantics of this POSIX string.
/// </remarks>
private static AdjustmentRule? TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset)
{
if (TZif_ParsePosixFormat(posixFormat,
out _,
out ReadOnlySpan<char> standardOffset,
out ReadOnlySpan<char> daylightSavingsName,
out ReadOnlySpan<char> daylightSavingsOffset,
out ReadOnlySpan<char> start,
out ReadOnlySpan<char> startTime,
out ReadOnlySpan<char> end,
out ReadOnlySpan<char> endTime))
{
// a valid posixFormat has at least standardName and standardOffset
TimeSpan? parsedBaseOffset = TZif_ParseOffsetString(standardOffset);
if (parsedBaseOffset.HasValue)
{
TimeSpan baseOffset = parsedBaseOffset.GetValueOrDefault().Negate(); // offsets are backwards in POSIX notation
baseOffset = TZif_CalculateTransitionOffsetFromBase(baseOffset, timeZoneBaseUtcOffset);
// having a daylightSavingsName means there is a DST rule
if (!daylightSavingsName.IsEmpty)
{
TimeSpan? parsedDaylightSavings = TZif_ParseOffsetString(daylightSavingsOffset);
TimeSpan daylightSavingsTimeSpan;
if (!parsedDaylightSavings.HasValue)
{
// default DST to 1 hour if it isn't specified
daylightSavingsTimeSpan = new TimeSpan(1, 0, 0);
}
else
{
daylightSavingsTimeSpan = parsedDaylightSavings.GetValueOrDefault().Negate(); // offsets are backwards in POSIX notation
daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, timeZoneBaseUtcOffset);
daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, baseOffset);
}
TransitionTime? dstStart = TZif_CreateTransitionTimeFromPosixRule(start, startTime);
TransitionTime? dstEnd = TZif_CreateTransitionTimeFromPosixRule(end, endTime);
if (dstStart == null || dstEnd == null)
{
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startTransitionDate,
DateTime.MaxValue,
daylightSavingsTimeSpan,
dstStart.GetValueOrDefault(),
dstEnd.GetValueOrDefault(),
baseOffset,
noDaylightTransitions: false);
}
else
{
// if there is no daylightSavingsName, the whole AdjustmentRule should be with no transitions - just the baseOffset
return AdjustmentRule.CreateAdjustmentRule(
startTransitionDate,
DateTime.MaxValue,
TimeSpan.Zero,
default,
default,
baseOffset,
noDaylightTransitions: true);
}
}
}
return null;
}
private static TimeSpan? TZif_ParseOffsetString(ReadOnlySpan<char> offset)
{
TimeSpan? result = null;
if (offset.Length > 0)
{
bool negative = offset[0] == '-';
if (negative || offset[0] == '+')
{
offset = offset.Slice(1);
}
// Try parsing just hours first.
// Note, TimeSpan.TryParseExact "%h" can't be used here because some time zones using values
// like "26" or "144" and TimeSpan parsing would turn that into 26 or 144 *days* instead of hours.
int hours;
if (int.TryParse(offset, out hours))
{
result = new TimeSpan(hours, 0, 0);
}
else
{
TimeSpan parsedTimeSpan;
if (TimeSpan.TryParseExact(offset, "g", CultureInfo.InvariantCulture, out parsedTimeSpan))
{
result = parsedTimeSpan;
}
}
if (result.HasValue && negative)
{
result = result.GetValueOrDefault().Negate();
}
}
return result;
}
private static DateTime ParseTimeOfDay(ReadOnlySpan<char> time)
{
DateTime timeOfDay;
TimeSpan? timeOffset = TZif_ParseOffsetString(time);
if (timeOffset.HasValue)
{
// This logic isn't correct and can't be corrected until https://github.com/dotnet/runtime/issues/14966 is fixed.
// Some time zones use time values like, "26", "144", or "-2".
// This allows the week to sometimes be week 4 and sometimes week 5 in the month.
// For now, strip off any 'days' in the offset, and just get the time of day correct
timeOffset = new TimeSpan(timeOffset.GetValueOrDefault().Hours, timeOffset.GetValueOrDefault().Minutes, timeOffset.GetValueOrDefault().Seconds);
if (timeOffset.GetValueOrDefault() < TimeSpan.Zero)
{
timeOfDay = new DateTime(1, 1, 2, 0, 0, 0);
}
else
{
timeOfDay = new DateTime(1, 1, 1, 0, 0, 0);
}
timeOfDay += timeOffset.GetValueOrDefault();
}
else
{
// default to 2AM.
timeOfDay = new DateTime(1, 1, 1, 2, 0, 0);
}
return timeOfDay;
}
private static TransitionTime? TZif_CreateTransitionTimeFromPosixRule(ReadOnlySpan<char> date, ReadOnlySpan<char> time)
{
if (date.IsEmpty)
{
return null;
}
if (date[0] == 'M')
{
// Mm.w.d
// This specifies day d of week w of month m. The day d must be between 0(Sunday) and 6.The week w must be between 1 and 5;
// week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12.
int month;
int week;
DayOfWeek day;
if (!TZif_ParseMDateRule(date, out month, out week, out day))
{
throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_UnparsablePosixMDateString, date.ToString()));
}
return TransitionTime.CreateFloatingDateRule(ParseTimeOfDay(time), month, week, day);
}
else
{
if (date[0] != 'J')
{
// should be n Julian day format.
// This specifies the Julian day, with n between 0 and 365. February 29 is counted in leap years.
//
// n would be a relative number from the beginning of the year. which should handle if the
// the year is a leap year or not.
//
// In leap year, n would be counted as:
//
// 0 30 31 59 60 90 335 365
// |-------Jan--------|-------Feb--------|-------Mar--------|....|-------Dec--------|
//
// while in non leap year we'll have
//
// 0 30 31 58 59 89 334 364
// |-------Jan--------|-------Feb--------|-------Mar--------|....|-------Dec--------|
//
// For example if n is specified as 60, this means in leap year the rule will start at Mar 1,
// while in non leap year the rule will start at Mar 2.
//
// This n Julian day format is very uncommon and mostly used for convenience to specify dates like January 1st
// which we can support without any major modification to the Adjustment rules. We'll support this rule for day
// numbers less than 59 (up to Feb 28). Otherwise we'll skip this POSIX rule.
// We've never encountered any time zone file using this format for days beyond Feb 28.
if (int.TryParse(date, out int julianDay) && julianDay < 59)
{
int d, m;
if (julianDay <= 30) // January
{
m = 1;
d = julianDay + 1;
}
else // February
{
m = 2;
d = julianDay - 30;
}
return TransitionTime.CreateFixedDateRule(ParseTimeOfDay(time), m, d);
}
// Since we can't support this rule, return null to indicate to skip the POSIX rule.
return null;
}
// Julian day
TZif_ParseJulianDay(date, out int month, out int day);
return TransitionTime.CreateFixedDateRule(ParseTimeOfDay(time), month, day);
}
}
/// <summary>
/// Parses a string like Jn into month and day values.
/// </summary>
private static void TZif_ParseJulianDay(ReadOnlySpan<char> date, out int month, out int day)
{
// Jn
// This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years.
Debug.Assert(!date.IsEmpty);
Debug.Assert(date[0] == 'J');
month = day = 0;
int index = 1;
if ((uint)index >= (uint)date.Length || !char.IsAsciiDigit(date[index]))
{
throw new InvalidTimeZoneException(SR.InvalidTimeZone_InvalidJulianDay);
}
int julianDay = 0;
do
{
julianDay = julianDay * 10 + (int)(date[index] - '0');
index++;
} while ((uint)index < (uint)date.Length && char.IsAsciiDigit(date[index]));
int[] days = GregorianCalendarHelper.DaysToMonth365;
if (julianDay == 0 || julianDay > days[days.Length - 1])
{
throw new InvalidTimeZoneException(SR.InvalidTimeZone_InvalidJulianDay);
}
int i = 1;
while (i < days.Length && julianDay > days[i])
{
i++;
}
Debug.Assert(i > 0 && i < days.Length);
month = i;
day = julianDay - days[i - 1];
}
/// <summary>
/// Parses a string like Mm.w.d into month, week and DayOfWeek values.
/// </summary>
/// <returns>
/// true if the parsing succeeded; otherwise, false.
/// </returns>
private static bool TZif_ParseMDateRule(ReadOnlySpan<char> dateRule, out int month, out int week, out DayOfWeek dayOfWeek)
{
if (dateRule[0] == 'M')
{
int monthWeekDotIndex = dateRule.IndexOf('.');
if (monthWeekDotIndex > 0)
{
ReadOnlySpan<char> weekDaySpan = dateRule.Slice(monthWeekDotIndex + 1);
int weekDayDotIndex = weekDaySpan.IndexOf('.');
if (weekDayDotIndex > 0)
{
if (int.TryParse(dateRule.Slice(1, monthWeekDotIndex - 1), out month) &&
int.TryParse(weekDaySpan.Slice(0, weekDayDotIndex), out week) &&
int.TryParse(weekDaySpan.Slice(weekDayDotIndex + 1), out int day))
{
dayOfWeek = (DayOfWeek)day;
return true;
}
}
}
}
month = 0;
week = 0;
dayOfWeek = default;
return false;
}
private static bool TZif_ParsePosixFormat(
ReadOnlySpan<char> posixFormat,
out ReadOnlySpan<char> standardName,
out ReadOnlySpan<char> standardOffset,
out ReadOnlySpan<char> daylightSavingsName,
out ReadOnlySpan<char> daylightSavingsOffset,
out ReadOnlySpan<char> start,
out ReadOnlySpan<char> startTime,
out ReadOnlySpan<char> end,
out ReadOnlySpan<char> endTime)
{
daylightSavingsOffset = null;
start = null;
startTime = null;
end = null;
endTime = null;
int index = 0;
standardName = TZif_ParsePosixName(posixFormat, ref index);
standardOffset = TZif_ParsePosixOffset(posixFormat, ref index);
daylightSavingsName = TZif_ParsePosixName(posixFormat, ref index);
if (!daylightSavingsName.IsEmpty)
{
daylightSavingsOffset = TZif_ParsePosixOffset(posixFormat, ref index);
if (index < posixFormat.Length && posixFormat[index] == ',')
{
index++;
TZif_ParsePosixDateTime(posixFormat, ref index, out start, out startTime);
if (index < posixFormat.Length && posixFormat[index] == ',')
{