TimeZoneInfo.cs 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Globalization;
  9. using System.Runtime.Serialization;
  10. using System.Threading;
  11. namespace System
  12. {
  13. //
  14. // DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset.
  15. // These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in. To avoid this
  16. // unwanted behavior in DateTime public APIs, DateTime internally passes the
  17. // TimeZoneInfoOptions.NoThrowOnInvalidTime flag to internal TimeZoneInfo APIs.
  18. //
  19. // In the future we can consider exposing similar options on the public TimeZoneInfo APIs if there is enough
  20. // demand for this alternate behavior.
  21. //
  22. [Flags]
  23. internal enum TimeZoneInfoOptions
  24. {
  25. None = 1,
  26. NoThrowOnInvalidTime = 2
  27. }
  28. [Serializable]
  29. [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  30. public sealed partial class TimeZoneInfo :
  31. #nullable disable // see comment on String
  32. IEquatable<TimeZoneInfo>,
  33. #nullable restore
  34. ISerializable, IDeserializationCallback
  35. {
  36. private enum TimeZoneInfoResult
  37. {
  38. Success = 0,
  39. TimeZoneNotFoundException = 1,
  40. InvalidTimeZoneException = 2,
  41. SecurityException = 3
  42. }
  43. private readonly string _id;
  44. private readonly string? _displayName;
  45. private readonly string? _standardDisplayName;
  46. private readonly string? _daylightDisplayName;
  47. private readonly TimeSpan _baseUtcOffset;
  48. private readonly bool _supportsDaylightSavingTime;
  49. private readonly AdjustmentRule[]? _adjustmentRules;
  50. // constants for TimeZoneInfo.Local and TimeZoneInfo.Utc
  51. private const string UtcId = "UTC";
  52. private const string LocalId = "Local";
  53. private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(UtcId, TimeSpan.Zero, "(UTC) Coordinated Universal Time", "Coordinated Universal Time");
  54. private static CachedData s_cachedData = new CachedData();
  55. //
  56. // All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
  57. //
  58. // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,
  59. // there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local.
  60. //
  61. private sealed partial class CachedData
  62. {
  63. private volatile TimeZoneInfo? _localTimeZone;
  64. private TimeZoneInfo CreateLocal()
  65. {
  66. lock (this)
  67. {
  68. TimeZoneInfo? timeZone = _localTimeZone;
  69. if (timeZone == null)
  70. {
  71. timeZone = GetLocalTimeZone(this);
  72. // this step is to break the reference equality
  73. // between TimeZoneInfo.Local and a second time zone
  74. // such as "Pacific Standard Time"
  75. timeZone = new TimeZoneInfo(
  76. timeZone._id,
  77. timeZone._baseUtcOffset,
  78. timeZone._displayName,
  79. timeZone._standardDisplayName,
  80. timeZone._daylightDisplayName,
  81. timeZone._adjustmentRules,
  82. disableDaylightSavingTime: false);
  83. _localTimeZone = timeZone;
  84. }
  85. return timeZone;
  86. }
  87. }
  88. public TimeZoneInfo Local => _localTimeZone ?? CreateLocal();
  89. /// <summary>
  90. /// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo.
  91. /// </summary>
  92. public DateTimeKind GetCorrespondingKind(TimeZoneInfo? timeZone)
  93. {
  94. // We check reference equality to see if 'this' is the same as
  95. // TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to
  96. // support setting the DateTime Kind property to 'Local' or
  97. // 'Utc' on the ConverTime(...) return value.
  98. //
  99. // Using reference equality instead of value equality was a
  100. // performance based design compromise. The reference equality
  101. // has much greater performance, but it reduces the number of
  102. // returned DateTime's that can be properly set as 'Local' or 'Utc'.
  103. //
  104. // For example, the user could be converting to the TimeZoneInfo returned
  105. // by FindSystemTimeZoneById("Pacific Standard Time") and their local
  106. // machine may be in Pacific time. If we used value equality to determine
  107. // the corresponding Kind then this conversion would be tagged as 'Local';
  108. // where as we are currently tagging the returned DateTime as 'Unspecified'
  109. // in this example. Only when the user passes in TimeZoneInfo.Local or
  110. // TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.
  111. //
  112. return
  113. ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc :
  114. ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local :
  115. DateTimeKind.Unspecified;
  116. }
  117. public Dictionary<string, TimeZoneInfo>? _systemTimeZones;
  118. public ReadOnlyCollection<TimeZoneInfo>? _readOnlySystemTimeZones;
  119. public bool _allSystemTimeZonesRead;
  120. }
  121. // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
  122. private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
  123. private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2);
  124. public string Id => _id;
  125. public string DisplayName => _displayName ?? string.Empty;
  126. public string StandardName => _standardDisplayName ?? string.Empty;
  127. public string DaylightName => _daylightDisplayName ?? string.Empty;
  128. public TimeSpan BaseUtcOffset => _baseUtcOffset;
  129. public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime;
  130. /// <summary>
  131. /// Returns an array of TimeSpan objects representing all of
  132. /// possible UTC offset values for this ambiguous time.
  133. /// </summary>
  134. public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset)
  135. {
  136. if (!SupportsDaylightSavingTime)
  137. {
  138. throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
  139. }
  140. DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;
  141. bool isAmbiguous = false;
  142. int? ruleIndex;
  143. AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);
  144. if (rule != null && rule.HasDaylightSaving)
  145. {
  146. DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
  147. isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
  148. }
  149. if (!isAmbiguous)
  150. {
  151. throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
  152. }
  153. // the passed in dateTime is ambiguous in this TimeZoneInfo instance
  154. TimeSpan[] timeSpans = new TimeSpan[2];
  155. TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;
  156. // the TimeSpan array must be sorted from least to greatest
  157. if (rule.DaylightDelta > TimeSpan.Zero)
  158. {
  159. timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
  160. timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
  161. }
  162. else
  163. {
  164. timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
  165. timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
  166. }
  167. return timeSpans;
  168. }
  169. /// <summary>
  170. /// Returns an array of TimeSpan objects representing all of
  171. /// possible UTC offset values for this ambiguous time.
  172. /// </summary>
  173. public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime)
  174. {
  175. if (!SupportsDaylightSavingTime)
  176. {
  177. throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
  178. }
  179. DateTime adjustedTime;
  180. if (dateTime.Kind == DateTimeKind.Local)
  181. {
  182. CachedData cachedData = s_cachedData;
  183. adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
  184. }
  185. else if (dateTime.Kind == DateTimeKind.Utc)
  186. {
  187. CachedData cachedData = s_cachedData;
  188. adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
  189. }
  190. else
  191. {
  192. adjustedTime = dateTime;
  193. }
  194. bool isAmbiguous = false;
  195. int? ruleIndex;
  196. AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);
  197. if (rule != null && rule.HasDaylightSaving)
  198. {
  199. DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
  200. isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
  201. }
  202. if (!isAmbiguous)
  203. {
  204. throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
  205. }
  206. // the passed in dateTime is ambiguous in this TimeZoneInfo instance
  207. TimeSpan[] timeSpans = new TimeSpan[2];
  208. TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;
  209. // the TimeSpan array must be sorted from least to greatest
  210. if (rule.DaylightDelta > TimeSpan.Zero)
  211. {
  212. timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
  213. timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
  214. }
  215. else
  216. {
  217. timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
  218. timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
  219. }
  220. return timeSpans;
  221. }
  222. // note the time is already adjusted
  223. private AdjustmentRule? GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex)
  224. {
  225. AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
  226. if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving)
  227. {
  228. // When using NoDaylightTransitions rules, each rule is only for one offset.
  229. // When looking for the Daylight savings rules, and we found the non-DST rule,
  230. // then we get the rule right before this rule.
  231. return GetPreviousAdjustmentRule(rule, ruleIndex);
  232. }
  233. return rule;
  234. }
  235. /// <summary>
  236. /// Gets the AdjustmentRule that is immediately preceding the specified rule.
  237. /// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,
  238. /// then the specified rule is returned.
  239. /// </summary>
  240. private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex)
  241. {
  242. Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules.");
  243. Debug.Assert(_adjustmentRules != null);
  244. if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length)
  245. {
  246. return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1];
  247. }
  248. AdjustmentRule result = rule;
  249. for (int i = 1; i < _adjustmentRules.Length; i++)
  250. {
  251. // use ReferenceEquals here instead of AdjustmentRule.Equals because
  252. // ReferenceEquals is much faster. This is safe because all the callers
  253. // of GetPreviousAdjustmentRule pass in a rule that was retrieved from
  254. // _adjustmentRules. A different approach will be needed if this ever changes.
  255. if (ReferenceEquals(rule, _adjustmentRules[i]))
  256. {
  257. result = _adjustmentRules[i - 1];
  258. break;
  259. }
  260. }
  261. return result;
  262. }
  263. /// <summary>
  264. /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
  265. /// </summary>
  266. public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) =>
  267. GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
  268. /// <summary>
  269. /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
  270. /// </summary>
  271. public TimeSpan GetUtcOffset(DateTime dateTime) =>
  272. GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
  273. // Shortcut for TimeZoneInfo.Local.GetUtcOffset
  274. internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
  275. {
  276. CachedData cachedData = s_cachedData;
  277. return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData);
  278. }
  279. /// <summary>
  280. /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
  281. /// </summary>
  282. internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) =>
  283. GetUtcOffset(dateTime, flags, s_cachedData);
  284. private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
  285. {
  286. if (dateTime.Kind == DateTimeKind.Local)
  287. {
  288. if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local)
  289. {
  290. //
  291. // normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
  292. //
  293. DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
  294. return GetUtcOffsetFromUtc(adjustedTime, this);
  295. }
  296. //
  297. // Fall through for TimeZoneInfo.Local.GetUtcOffset(date)
  298. // to handle an edge case with Invalid-Times for DateTime formatting:
  299. //
  300. // Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00"
  301. //
  302. // By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc
  303. // the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an
  304. // interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output:
  305. //
  306. // 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00"
  307. // 2) converted to UTC "2007-03-11T10:00:00.0000000Z"
  308. // 3) offset returned "2007-03-11T03:00:00.0000000-07:00"
  309. //
  310. }
  311. else if (dateTime.Kind == DateTimeKind.Utc)
  312. {
  313. if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
  314. {
  315. return _baseUtcOffset;
  316. }
  317. else
  318. {
  319. //
  320. // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
  321. // special Loss-Less case.
  322. //
  323. return GetUtcOffsetFromUtc(dateTime, this);
  324. }
  325. }
  326. return GetUtcOffset(dateTime, this);
  327. }
  328. /// <summary>
  329. /// Returns true if the time is during the ambiguous time period
  330. /// for the current TimeZoneInfo instance.
  331. /// </summary>
  332. public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset)
  333. {
  334. if (!_supportsDaylightSavingTime)
  335. {
  336. return false;
  337. }
  338. DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this);
  339. return IsAmbiguousTime(adjustedTime.DateTime);
  340. }
  341. /// <summary>
  342. /// Returns true if the time is during the ambiguous time period
  343. /// for the current TimeZoneInfo instance.
  344. /// </summary>
  345. public bool IsAmbiguousTime(DateTime dateTime) =>
  346. IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
  347. /// <summary>
  348. /// Returns true if the time is during the ambiguous time period
  349. /// for the current TimeZoneInfo instance.
  350. /// </summary>
  351. internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags)
  352. {
  353. if (!_supportsDaylightSavingTime)
  354. {
  355. return false;
  356. }
  357. CachedData cachedData = s_cachedData;
  358. DateTime adjustedTime =
  359. dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) :
  360. dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) :
  361. dateTime;
  362. int? ruleIndex;
  363. AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
  364. if (rule != null && rule.HasDaylightSaving)
  365. {
  366. DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
  367. return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
  368. }
  369. return false;
  370. }
  371. /// <summary>
  372. /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
  373. /// </summary>
  374. public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset)
  375. {
  376. bool isDaylightSavingTime;
  377. GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime);
  378. return isDaylightSavingTime;
  379. }
  380. /// <summary>
  381. /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
  382. /// </summary>
  383. public bool IsDaylightSavingTime(DateTime dateTime) =>
  384. IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
  385. /// <summary>
  386. /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
  387. /// </summary>
  388. internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) =>
  389. IsDaylightSavingTime(dateTime, flags, s_cachedData);
  390. private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
  391. {
  392. //
  393. // dateTime.Kind is UTC, then time will be converted from UTC
  394. // into current instance's timezone
  395. // dateTime.Kind is Local, then time will be converted from Local
  396. // into current instance's timezone
  397. // dateTime.Kind is UnSpecified, then time is already in
  398. // current instance's timezone
  399. //
  400. // Our DateTime handles ambiguous times, (one is in the daylight and
  401. // one is in standard.) If a new DateTime is constructed during ambiguous
  402. // time, it is defaulted to "Standard" (i.e. this will return false).
  403. // For Invalid times, we will return false
  404. if (!_supportsDaylightSavingTime || _adjustmentRules == null)
  405. {
  406. return false;
  407. }
  408. DateTime adjustedTime;
  409. //
  410. // handle any Local/Utc special cases...
  411. //
  412. if (dateTime.Kind == DateTimeKind.Local)
  413. {
  414. adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
  415. }
  416. else if (dateTime.Kind == DateTimeKind.Utc)
  417. {
  418. if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
  419. {
  420. // simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags);
  421. return false;
  422. }
  423. else
  424. {
  425. //
  426. // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
  427. // special Loss-Less case.
  428. //
  429. bool isDaylightSavings;
  430. GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings);
  431. return isDaylightSavings;
  432. }
  433. }
  434. else
  435. {
  436. adjustedTime = dateTime;
  437. }
  438. //
  439. // handle the normal cases...
  440. //
  441. int? ruleIndex;
  442. AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
  443. if (rule != null && rule.HasDaylightSaving)
  444. {
  445. DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
  446. return GetIsDaylightSavings(adjustedTime, rule, daylightTime);
  447. }
  448. else
  449. {
  450. return false;
  451. }
  452. }
  453. /// <summary>
  454. /// Returns true when dateTime falls into a "hole in time".
  455. /// </summary>
  456. public bool IsInvalidTime(DateTime dateTime)
  457. {
  458. bool isInvalid = false;
  459. if ((dateTime.Kind == DateTimeKind.Unspecified) ||
  460. (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))
  461. {
  462. // only check Unspecified and (Local when this TimeZoneInfo instance is Local)
  463. int? ruleIndex;
  464. AdjustmentRule? rule = GetAdjustmentRuleForTime(dateTime, out ruleIndex);
  465. if (rule != null && rule.HasDaylightSaving)
  466. {
  467. DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex);
  468. isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
  469. }
  470. else
  471. {
  472. isInvalid = false;
  473. }
  474. }
  475. return isInvalid;
  476. }
  477. /// <summary>
  478. /// Clears data from static members.
  479. /// </summary>
  480. public static void ClearCachedData()
  481. {
  482. // Clear a fresh instance of cached data
  483. s_cachedData = new CachedData();
  484. }
  485. /// <summary>
  486. /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
  487. /// </summary>
  488. public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) =>
  489. ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
  490. /// <summary>
  491. /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
  492. /// </summary>
  493. public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) =>
  494. ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
  495. /// <summary>
  496. /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
  497. /// </summary>
  498. public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
  499. {
  500. if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase))
  501. {
  502. // TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData.
  503. // Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.
  504. // Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't
  505. // be reference equal to the new TimeZoneInfo.Local
  506. //
  507. CachedData cachedData = s_cachedData;
  508. return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
  509. }
  510. else if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase))
  511. {
  512. return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData);
  513. }
  514. else
  515. {
  516. return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));
  517. }
  518. }
  519. /// <summary>
  520. /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
  521. /// </summary>
  522. public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
  523. {
  524. if (destinationTimeZone == null)
  525. {
  526. throw new ArgumentNullException(nameof(destinationTimeZone));
  527. }
  528. // calculate the destination time zone offset
  529. DateTime utcDateTime = dateTimeOffset.UtcDateTime;
  530. TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);
  531. // check for overflow
  532. long ticks = utcDateTime.Ticks + destinationOffset.Ticks;
  533. return
  534. ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue :
  535. ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue :
  536. new DateTimeOffset(ticks, destinationOffset);
  537. }
  538. /// <summary>
  539. /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
  540. /// </summary>
  541. public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone)
  542. {
  543. if (destinationTimeZone == null)
  544. {
  545. throw new ArgumentNullException(nameof(destinationTimeZone));
  546. }
  547. // Special case to give a way clearing the cache without exposing ClearCachedData()
  548. if (dateTime.Ticks == 0)
  549. {
  550. ClearCachedData();
  551. }
  552. CachedData cachedData = s_cachedData;
  553. TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local;
  554. return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
  555. }
  556. /// <summary>
  557. /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
  558. /// </summary>
  559. public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) =>
  560. ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
  561. /// <summary>
  562. /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
  563. /// </summary>
  564. internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) =>
  565. ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
  566. private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData)
  567. {
  568. if (sourceTimeZone == null)
  569. {
  570. throw new ArgumentNullException(nameof(sourceTimeZone));
  571. }
  572. if (destinationTimeZone == null)
  573. {
  574. throw new ArgumentNullException(nameof(destinationTimeZone));
  575. }
  576. DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
  577. if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
  578. {
  579. throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone));
  580. }
  581. //
  582. // check to see if the DateTime is in an invalid time range. This check
  583. // requires the current AdjustmentRule and DaylightTime - which are also
  584. // needed to calculate 'sourceOffset' in the normal conversion case.
  585. // By calculating the 'sourceOffset' here we improve the
  586. // performance for the normal case at the expense of the 'ArgumentException'
  587. // case and Loss-less Local special cases.
  588. //
  589. int? sourceRuleIndex;
  590. AdjustmentRule? sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out sourceRuleIndex);
  591. TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;
  592. if (sourceRule != null)
  593. {
  594. sourceOffset += sourceRule.BaseUtcOffsetDelta;
  595. if (sourceRule.HasDaylightSaving)
  596. {
  597. bool sourceIsDaylightSavings = false;
  598. DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule, sourceRuleIndex);
  599. // 'dateTime' might be in an invalid time range since it is in an AdjustmentRule
  600. // period that supports DST
  601. if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))
  602. {
  603. throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime));
  604. }
  605. sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime);
  606. // adjust the sourceOffset according to the Adjustment Rule / Daylight Saving Rule
  607. sourceOffset += (sourceIsDaylightSavings ? sourceRule.DaylightDelta : TimeSpan.Zero /*FUTURE: sourceRule.StandardDelta*/);
  608. }
  609. }
  610. DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone);
  611. // handle the special case of Loss-less Local->Local and UTC->UTC)
  612. if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind)
  613. {
  614. return dateTime;
  615. }
  616. long utcTicks = dateTime.Ticks - sourceOffset.Ticks;
  617. // handle the normal case by converting from 'source' to UTC and then to 'target'
  618. bool isAmbiguousLocalDst;
  619. DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out isAmbiguousLocalDst);
  620. if (targetKind == DateTimeKind.Local)
  621. {
  622. // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
  623. // time is in a repeated hour so that it can be passed to the DateTime constructor.
  624. return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);
  625. }
  626. else
  627. {
  628. return new DateTime(targetConverted.Ticks, targetKind);
  629. }
  630. }
  631. /// <summary>
  632. /// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone.
  633. /// </summary>
  634. public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) =>
  635. ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
  636. /// <summary>
  637. /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
  638. /// </summary>
  639. public static DateTime ConvertTimeToUtc(DateTime dateTime)
  640. {
  641. if (dateTime.Kind == DateTimeKind.Utc)
  642. {
  643. return dateTime;
  644. }
  645. CachedData cachedData = s_cachedData;
  646. return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
  647. }
  648. /// <summary>
  649. /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
  650. /// </summary>
  651. internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
  652. {
  653. if (dateTime.Kind == DateTimeKind.Utc)
  654. {
  655. return dateTime;
  656. }
  657. CachedData cachedData = s_cachedData;
  658. return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);
  659. }
  660. /// <summary>
  661. /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
  662. /// </summary>
  663. public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) =>
  664. ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData);
  665. /// <summary>
  666. /// Returns value equality. Equals does not compare any localizable
  667. /// String objects (DisplayName, StandardName, DaylightName).
  668. /// </summary>
  669. public bool Equals(TimeZoneInfo? other) =>
  670. other != null &&
  671. string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) &&
  672. HasSameRules(other);
  673. public override bool Equals(object? obj) => Equals(obj as TimeZoneInfo);
  674. public static TimeZoneInfo FromSerializedString(string source)
  675. {
  676. if (source == null)
  677. {
  678. throw new ArgumentNullException(nameof(source));
  679. }
  680. if (source.Length == 0)
  681. {
  682. throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));
  683. }
  684. return StringSerializer.GetDeserializedTimeZoneInfo(source);
  685. }
  686. public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id);
  687. /// <summary>
  688. /// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's
  689. /// from the local machine. The entries in the collection are sorted by
  690. /// <see cref="DisplayName"/>.
  691. /// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.
  692. /// </summary>
  693. public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
  694. {
  695. CachedData cachedData = s_cachedData;
  696. lock (cachedData)
  697. {
  698. if (cachedData._readOnlySystemTimeZones == null)
  699. {
  700. PopulateAllSystemTimeZones(cachedData);
  701. cachedData._allSystemTimeZonesRead = true;
  702. List<TimeZoneInfo> list;
  703. if (cachedData._systemTimeZones != null)
  704. {
  705. // return a collection of the cached system time zones
  706. list = new List<TimeZoneInfo>(cachedData._systemTimeZones.Values);
  707. }
  708. else
  709. {
  710. // return an empty collection
  711. list = new List<TimeZoneInfo>();
  712. }
  713. // sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
  714. list.Sort((x, y) =>
  715. {
  716. // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
  717. int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
  718. return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
  719. });
  720. cachedData._readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
  721. }
  722. }
  723. return cachedData._readOnlySystemTimeZones;
  724. }
  725. /// <summary>
  726. /// Value equality on the "adjustmentRules" array
  727. /// </summary>
  728. public bool HasSameRules(TimeZoneInfo other)
  729. {
  730. if (other == null)
  731. {
  732. throw new ArgumentNullException(nameof(other));
  733. }
  734. // check the utcOffset and supportsDaylightSavingTime members
  735. if (_baseUtcOffset != other._baseUtcOffset ||
  736. _supportsDaylightSavingTime != other._supportsDaylightSavingTime)
  737. {
  738. return false;
  739. }
  740. bool sameRules;
  741. AdjustmentRule[]? currentRules = _adjustmentRules;
  742. AdjustmentRule[]? otherRules = other._adjustmentRules;
  743. sameRules =
  744. (currentRules == null && otherRules == null) ||
  745. (currentRules != null && otherRules != null);
  746. if (!sameRules)
  747. {
  748. // AdjustmentRule array mismatch
  749. return false;
  750. }
  751. if (currentRules != null)
  752. {
  753. if (currentRules.Length != otherRules!.Length)
  754. {
  755. // AdjustmentRule array length mismatch
  756. return false;
  757. }
  758. for (int i = 0; i < currentRules.Length; i++)
  759. {
  760. if (!(currentRules[i]).Equals(otherRules[i]))
  761. {
  762. // AdjustmentRule value-equality mismatch
  763. return false;
  764. }
  765. }
  766. }
  767. return sameRules;
  768. }
  769. /// <summary>
  770. /// Returns a TimeZoneInfo instance that represents the local time on the machine.
  771. /// Accessing this property may throw InvalidTimeZoneException or COMException
  772. /// if the machine is in an unstable or corrupt state.
  773. /// </summary>
  774. public static TimeZoneInfo Local => s_cachedData.Local;
  775. //
  776. // ToSerializedString -
  777. //
  778. // "TimeZoneInfo" := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N]
  779. //
  780. // "TimeZoneInfo Data" := <_id>;<_baseUtcOffset>;<_displayName>;
  781. // <_standardDisplayName>;<_daylightDispayName>;
  782. //
  783. // "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>;
  784. // [TransitionTime Data DST Start]
  785. // [TransitionTime Data DST End]
  786. //
  787. // "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day>
  788. //
  789. public string ToSerializedString() => StringSerializer.GetSerializedString(this);
  790. /// <summary>
  791. /// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US &amp; Canada); Tijuana"
  792. /// </summary>
  793. public override string ToString() => DisplayName;
  794. /// <summary>
  795. /// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)
  796. /// </summary>
  797. public static TimeZoneInfo Utc => s_utcTimeZone;
  798. private TimeZoneInfo(
  799. string id,
  800. TimeSpan baseUtcOffset,
  801. string? displayName,
  802. string? standardDisplayName,
  803. string? daylightDisplayName,
  804. AdjustmentRule[]? adjustmentRules,
  805. bool disableDaylightSavingTime)
  806. {
  807. bool adjustmentRulesSupportDst;
  808. ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
  809. _id = id;
  810. _baseUtcOffset = baseUtcOffset;
  811. _displayName = displayName;
  812. _standardDisplayName = standardDisplayName;
  813. _daylightDisplayName = disableDaylightSavingTime ? null : daylightDisplayName;
  814. _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
  815. _adjustmentRules = adjustmentRules;
  816. }
  817. /// <summary>
  818. /// Returns a simple TimeZoneInfo instance that does not support Daylight Saving Time.
  819. /// </summary>
  820. public static TimeZoneInfo CreateCustomTimeZone(
  821. string id,
  822. TimeSpan baseUtcOffset,
  823. string? displayName,
  824. string? standardDisplayName)
  825. {
  826. return new TimeZoneInfo(
  827. id,
  828. baseUtcOffset,
  829. displayName,
  830. standardDisplayName,
  831. standardDisplayName,
  832. adjustmentRules: null,
  833. disableDaylightSavingTime: false);
  834. }
  835. /// <summary>
  836. /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
  837. /// </summary>
  838. public static TimeZoneInfo CreateCustomTimeZone(
  839. string id,
  840. TimeSpan baseUtcOffset,
  841. string? displayName,
  842. string? standardDisplayName,
  843. string? daylightDisplayName,
  844. AdjustmentRule[]? adjustmentRules)
  845. {
  846. return CreateCustomTimeZone(
  847. id,
  848. baseUtcOffset,
  849. displayName,
  850. standardDisplayName,
  851. daylightDisplayName,
  852. adjustmentRules,
  853. disableDaylightSavingTime: false);
  854. }
  855. /// <summary>
  856. /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
  857. /// </summary>
  858. public static TimeZoneInfo CreateCustomTimeZone(
  859. string id,
  860. TimeSpan baseUtcOffset,
  861. string? displayName,
  862. string? standardDisplayName,
  863. string? daylightDisplayName,
  864. AdjustmentRule[]? adjustmentRules,
  865. bool disableDaylightSavingTime)
  866. {
  867. if (!disableDaylightSavingTime && adjustmentRules?.Length > 0)
  868. {
  869. adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
  870. }
  871. return new TimeZoneInfo(
  872. id,
  873. baseUtcOffset,
  874. displayName,
  875. standardDisplayName,
  876. daylightDisplayName,
  877. adjustmentRules,
  878. disableDaylightSavingTime);
  879. }
  880. void IDeserializationCallback.OnDeserialization(object? sender)
  881. {
  882. try
  883. {
  884. bool adjustmentRulesSupportDst;
  885. ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out adjustmentRulesSupportDst);
  886. if (adjustmentRulesSupportDst != _supportsDaylightSavingTime)
  887. {
  888. throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime"));
  889. }
  890. }
  891. catch (ArgumentException e)
  892. {
  893. throw new SerializationException(SR.Serialization_InvalidData, e);
  894. }
  895. catch (InvalidTimeZoneException e)
  896. {
  897. throw new SerializationException(SR.Serialization_InvalidData, e);
  898. }
  899. }
  900. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  901. {
  902. if (info == null)
  903. {
  904. throw new ArgumentNullException(nameof(info));
  905. }
  906. info.AddValue("Id", _id); // Do not rename (binary serialization)
  907. info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization)
  908. info.AddValue("StandardName", _standardDisplayName); // Do not rename (binary serialization)
  909. info.AddValue("DaylightName", _daylightDisplayName); // Do not rename (binary serialization)
  910. info.AddValue("BaseUtcOffset", _baseUtcOffset); // Do not rename (binary serialization)
  911. info.AddValue("AdjustmentRules", _adjustmentRules); // Do not rename (binary serialization)
  912. info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization)
  913. }
  914. private TimeZoneInfo(SerializationInfo info, StreamingContext context)
  915. {
  916. if (info == null)
  917. {
  918. throw new ArgumentNullException(nameof(info));
  919. }
  920. _id = (string)info.GetValue("Id", typeof(string))!; // Do not rename (binary serialization)
  921. _displayName = (string?)info.GetValue("DisplayName", typeof(string)); // Do not rename (binary serialization)
  922. _standardDisplayName = (string?)info.GetValue("StandardName", typeof(string)); // Do not rename (binary serialization)
  923. _daylightDisplayName = (string?)info.GetValue("DaylightName", typeof(string)); // Do not rename (binary serialization)
  924. _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan))!; // Do not rename (binary serialization)
  925. _adjustmentRules = (AdjustmentRule[]?)info.GetValue("AdjustmentRules", typeof(AdjustmentRule[])); // Do not rename (binary serialization)
  926. _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool))!; // Do not rename (binary serialization)
  927. }
  928. private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex)
  929. {
  930. AdjustmentRule? result = GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, ruleIndex: out ruleIndex);
  931. Debug.Assert(result == null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set.");
  932. return result;
  933. }
  934. private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex)
  935. {
  936. if (_adjustmentRules == null || _adjustmentRules.Length == 0)
  937. {
  938. ruleIndex = null;
  939. return null;
  940. }
  941. // Only check the whole-date portion of the dateTime for DateTimeKind.Unspecified rules -
  942. // This is because the AdjustmentRule DateStart & DateEnd are stored as
  943. // Date-only values {4/2/2006 - 10/28/2006} but actually represent the
  944. // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}
  945. DateTime date = dateTimeisUtc ?
  946. (dateTime + BaseUtcOffset).Date :
  947. dateTime.Date;
  948. int low = 0;
  949. int high = _adjustmentRules.Length - 1;
  950. while (low <= high)
  951. {
  952. int median = low + ((high - low) >> 1);
  953. AdjustmentRule rule = _adjustmentRules[median];
  954. AdjustmentRule previousRule = median > 0 ? _adjustmentRules[median - 1] : rule;
  955. int compareResult = CompareAdjustmentRuleToDateTime(rule, previousRule, dateTime, date, dateTimeisUtc);
  956. if (compareResult == 0)
  957. {
  958. ruleIndex = median;
  959. return rule;
  960. }
  961. else if (compareResult < 0)
  962. {
  963. low = median + 1;
  964. }
  965. else
  966. {
  967. high = median - 1;
  968. }
  969. }
  970. ruleIndex = null;
  971. return null;
  972. }
  973. /// <summary>
  974. /// Determines if 'rule' is the correct AdjustmentRule for the given dateTime.
  975. /// </summary>
  976. /// <returns>
  977. /// A value less than zero if rule is for times before dateTime.
  978. /// Zero if rule is correct for dateTime.
  979. /// A value greater than zero if rule is for times after dateTime.
  980. /// </returns>
  981. private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule,
  982. DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc)
  983. {
  984. bool isAfterStart;
  985. if (rule.DateStart.Kind == DateTimeKind.Utc)
  986. {
  987. DateTime dateTimeToCompare = dateTimeisUtc ?
  988. dateTime :
  989. // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches"
  990. // is based on the previous rule's offset
  991. ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
  992. isAfterStart = dateTimeToCompare >= rule.DateStart;
  993. }
  994. else
  995. {
  996. // if the rule's DateStart is Unspecified, then use the whole-date portion
  997. isAfterStart = dateOnly >= rule.DateStart;
  998. }
  999. if (!isAfterStart)
  1000. {
  1001. return 1;
  1002. }
  1003. bool isBeforeEnd;
  1004. if (rule.DateEnd.Kind == DateTimeKind.Utc)
  1005. {
  1006. DateTime dateTimeToCompare = dateTimeisUtc ?
  1007. dateTime :
  1008. ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
  1009. isBeforeEnd = dateTimeToCompare <= rule.DateEnd;
  1010. }
  1011. else
  1012. {
  1013. // if the rule's DateEnd is Unspecified, then use the whole-date portion
  1014. isBeforeEnd = dateOnly <= rule.DateEnd;
  1015. }
  1016. return isBeforeEnd ? 0 : -1;
  1017. }
  1018. /// <summary>
  1019. /// Converts the dateTime to UTC using the specified deltas.
  1020. /// </summary>
  1021. private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
  1022. ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true);
  1023. /// <summary>
  1024. /// Converts the dateTime from UTC using the specified deltas.
  1025. /// </summary>
  1026. private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
  1027. ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false);
  1028. /// <summary>
  1029. /// Converts the dateTime to or from UTC using the specified deltas.
  1030. /// </summary>
  1031. private DateTime ConvertToFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta, bool convertToUtc)
  1032. {
  1033. TimeSpan offset = BaseUtcOffset + daylightDelta + baseUtcOffsetDelta;
  1034. if (convertToUtc)
  1035. {
  1036. offset = offset.Negate();
  1037. }
  1038. long ticks = dateTime.Ticks + offset.Ticks;
  1039. return
  1040. ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
  1041. ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
  1042. new DateTime(ticks);
  1043. }
  1044. /// <summary>
  1045. /// Helper function that converts a dateTime from UTC into the destinationTimeZone
  1046. /// - Returns DateTime.MaxValue when the converted value is too large.
  1047. /// - Returns DateTime.MinValue when the converted value is too small.
  1048. /// </summary>
  1049. private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst)
  1050. {
  1051. // used to calculate the UTC offset in the destinationTimeZone
  1052. DateTime utcConverted =
  1053. ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
  1054. ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
  1055. new DateTime(ticks);
  1056. // verify the time is between MinValue and MaxValue in the new time zone
  1057. TimeSpan offset = GetUtcOffsetFromUtc(utcConverted, destinationTimeZone, out isAmbiguousLocalDst);
  1058. ticks += offset.Ticks;
  1059. return
  1060. ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
  1061. ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
  1062. new DateTime(ticks);
  1063. }
  1064. /// <summary>
  1065. /// Helper function that returns a DaylightTime from a year and AdjustmentRule.
  1066. /// </summary>
  1067. private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? ruleIndex)
  1068. {
  1069. TimeSpan delta = rule.DaylightDelta;
  1070. DateTime startTime;
  1071. DateTime endTime;
  1072. if (rule.NoDaylightTransitions)
  1073. {
  1074. // NoDaylightTransitions rules don't use DaylightTransition Start and End, instead
  1075. // the DateStart and DateEnd are UTC times that represent when daylight savings time changes.
  1076. // Convert the UTC times into adjusted time zone times.
  1077. // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule
  1078. AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);
  1079. startTime = ConvertFromUtc(rule.DateStart, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
  1080. endTime = ConvertFromUtc(rule.DateEnd, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
  1081. }
  1082. else
  1083. {
  1084. startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
  1085. endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
  1086. }
  1087. return new DaylightTimeStruct(startTime, endTime, delta);
  1088. }
  1089. /// <summary>
  1090. /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
  1091. /// This function assumes the dateTime and AdjustmentRule are both in the same time zone.
  1092. /// </summary>
  1093. private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
  1094. {
  1095. if (rule == null)
  1096. {
  1097. return false;
  1098. }
  1099. DateTime startTime;
  1100. DateTime endTime;
  1101. if (time.Kind == DateTimeKind.Local)
  1102. {
  1103. // startTime and endTime represent the period from either the start of
  1104. // DST to the end and ***includes*** the potentially overlapped times
  1105. startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
  1106. new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
  1107. daylightTime.Start + daylightTime.Delta;
  1108. endTime = rule.IsEndDateMarkerForEndOfYear() ?
  1109. new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
  1110. daylightTime.End;
  1111. }
  1112. else
  1113. {
  1114. // startTime and endTime represent the period from either the start of DST to the end and
  1115. // ***does not include*** the potentially overlapped times
  1116. //
  1117. // -=-=-=-=-=- Pacific Standard Time -=-=-=-=-=-=-
  1118. // April 2, 2006 October 29, 2006
  1119. // 2AM 3AM 1AM 2AM
  1120. // | +1 hr | | -1 hr |
  1121. // | <invalid time> | | <ambiguous time> |
  1122. // [========== DST ========>)
  1123. //
  1124. // -=-=-=-=-=- Some Weird Time Zone -=-=-=-=-=-=-
  1125. // April 2, 2006 October 29, 2006
  1126. // 1AM 2AM 2AM 3AM
  1127. // | -1 hr | | +1 hr |
  1128. // | <ambiguous time> | | <invalid time> |
  1129. // [======== DST ========>)
  1130. //
  1131. bool invalidAtStart = rule.DaylightDelta > TimeSpan.Zero;
  1132. startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
  1133. new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
  1134. daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */
  1135. endTime = rule.IsEndDateMarkerForEndOfYear() ?
  1136. new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
  1137. daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero);
  1138. }
  1139. bool isDst = CheckIsDst(startTime, time, endTime, false, rule);
  1140. // If this date was previously converted from a UTC date and we were able to detect that the local
  1141. // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.
  1142. if (isDst && time.Kind == DateTimeKind.Local)
  1143. {
  1144. // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the
  1145. // clock back. It is theoretically possible to have a positive delta, (which would really be daylight
  1146. // reduction time), where you would have to wind the clock back in the begnning.
  1147. if (GetIsAmbiguousTime(time, rule, daylightTime))
  1148. {
  1149. isDst = time.IsAmbiguousDaylightSavingTime();
  1150. }
  1151. }
  1152. return isDst;
  1153. }
  1154. /// <summary>
  1155. /// Gets the offset that should be used to calculate DST start times from a UTC time.
  1156. /// </summary>
  1157. private TimeSpan GetDaylightSavingsStartOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule, int? ruleIndex)
  1158. {
  1159. if (rule.NoDaylightTransitions)
  1160. {
  1161. // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule
  1162. AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);
  1163. return baseUtcOffset + previousRule.BaseUtcOffsetDelta + previousRule.DaylightDelta;
  1164. }
  1165. else
  1166. {
  1167. return baseUtcOffset + rule.BaseUtcOffsetDelta; /* FUTURE: + rule.StandardDelta; */
  1168. }
  1169. }
  1170. /// <summary>
  1171. /// Gets the offset that should be used to calculate DST end times from a UTC time.
  1172. /// </summary>
  1173. private TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule)
  1174. {
  1175. // NOTE: even NoDaylightTransitions rules use this logic since DST ends w.r.t. the current rule
  1176. return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
  1177. }
  1178. /// <summary>
  1179. /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
  1180. /// This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone.
  1181. /// </summary>
  1182. private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, int? ruleIndex, out bool isAmbiguousLocalDst, TimeZoneInfo zone)
  1183. {
  1184. isAmbiguousLocalDst = false;
  1185. if (rule == null)
  1186. {
  1187. return false;
  1188. }
  1189. // Get the daylight changes for the year of the specified time.
  1190. DaylightTimeStruct daylightTime = zone.GetDaylightTime(year, rule, ruleIndex);
  1191. // The start and end times represent the range of universal times that are in DST for that year.
  1192. // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
  1193. // the unusual case of a negative daylight savings delta.
  1194. // We need to handle the case if the current rule has daylight saving end by the end of year. If so, we need to check if next year starts with daylight saving on
  1195. // and get the actual daylight saving end time. Here is example for such case:
  1196. // Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone.
  1197. // In 2011 the daylight saving will go through the end of the year. If we use the end of 2011 as the daylight saving end,
  1198. // that will fail the conversion because the UTC time +4 hours (3 hours for the zone UTC offset and 1 hour for daylight saving) will move us to the next year "1/1/2012 12:00 AM",
  1199. // checking against the end of 2011 will tell we are not in daylight saving which is wrong and the conversion will be off by one hour.
  1200. // Note we handle the similar case when rule year start with daylight saving and previous year end with daylight saving.
  1201. bool ignoreYearAdjustment = false;
  1202. TimeSpan dstStartOffset = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule, ruleIndex);
  1203. DateTime startTime;
  1204. if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year)
  1205. {
  1206. int? previousYearRuleIndex;
  1207. AdjustmentRule? previousYearRule = zone.GetAdjustmentRuleForTime(
  1208. new DateTime(daylightTime.Start.Year - 1, 12, 31),
  1209. out previousYearRuleIndex);
  1210. if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear())
  1211. {
  1212. DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime(
  1213. daylightTime.Start.Year - 1,
  1214. previousYearRule,
  1215. previousYearRuleIndex);
  1216. startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta;
  1217. ignoreYearAdjustment = true;
  1218. }
  1219. else
  1220. {
  1221. startTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - dstStartOffset;
  1222. }
  1223. }
  1224. else
  1225. {
  1226. startTime = daylightTime.Start - dstStartOffset;
  1227. }
  1228. TimeSpan dstEndOffset = zone.GetDaylightSavingsEndOffsetFromUtc(utc, rule);
  1229. DateTime endTime;
  1230. if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year)
  1231. {
  1232. int? nextYearRuleIndex;
  1233. AdjustmentRule? nextYearRule = zone.GetAdjustmentRuleForTime(
  1234. new DateTime(daylightTime.End.Year + 1, 1, 1),
  1235. out nextYearRuleIndex);
  1236. if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear())
  1237. {
  1238. if (nextYearRule.IsEndDateMarkerForEndOfYear())
  1239. {
  1240. // next year end with daylight saving on too
  1241. endTime = new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
  1242. }
  1243. else
  1244. {
  1245. DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime(
  1246. daylightTime.End.Year + 1,
  1247. nextYearRule,
  1248. nextYearRuleIndex);
  1249. endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
  1250. }
  1251. ignoreYearAdjustment = true;
  1252. }
  1253. else
  1254. {
  1255. endTime = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) - dstEndOffset;
  1256. }
  1257. }
  1258. else
  1259. {
  1260. endTime = daylightTime.End - dstEndOffset;
  1261. }
  1262. DateTime ambiguousStart;
  1263. DateTime ambiguousEnd;
  1264. if (daylightTime.Delta.Ticks > 0)
  1265. {
  1266. ambiguousStart = endTime - daylightTime.Delta;
  1267. ambiguousEnd = endTime;
  1268. }
  1269. else
  1270. {
  1271. ambiguousStart = startTime;
  1272. ambiguousEnd = startTime - daylightTime.Delta;
  1273. }
  1274. bool isDst = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule);
  1275. // See if the resulting local time becomes ambiguous. This must be captured here or the
  1276. // DateTime will not be able to round-trip back to UTC accurately.
  1277. if (isDst)
  1278. {
  1279. isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
  1280. if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year)
  1281. {
  1282. // there exists an extreme corner case where the start or end period is on a year boundary and
  1283. // because of this the comparison above might have been performed for a year-early or a year-later
  1284. // than it should have been.
  1285. DateTime ambiguousStartModified;
  1286. DateTime ambiguousEndModified;
  1287. try
  1288. {
  1289. ambiguousStartModified = ambiguousStart.AddYears(1);
  1290. ambiguousEndModified = ambiguousEnd.AddYears(1);
  1291. isAmbiguousLocalDst = (time >= ambiguousStartModified && time < ambiguousEndModified);
  1292. }
  1293. catch (ArgumentOutOfRangeException) { }
  1294. if (!isAmbiguousLocalDst)
  1295. {
  1296. try
  1297. {
  1298. ambiguousStartModified = ambiguousStart.AddYears(-1);
  1299. ambiguousEndModified = ambiguousEnd.AddYears(-1);
  1300. isAmbiguousLocalDst = (time >= ambiguousStartModified && time < ambiguousEndModified);
  1301. }
  1302. catch (ArgumentOutOfRangeException) { }
  1303. }
  1304. }
  1305. }
  1306. return isDst;
  1307. }
  1308. private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule)
  1309. {
  1310. // NoDaylightTransitions AdjustmentRules should never get their year adjusted since they adjust the offset for the
  1311. // entire time period - which may be for multiple years
  1312. if (!ignoreYearAdjustment && !rule.NoDaylightTransitions)
  1313. {
  1314. int startTimeYear = startTime.Year;
  1315. int endTimeYear = endTime.Year;
  1316. if (startTimeYear != endTimeYear)
  1317. {
  1318. endTime = endTime.AddYears(startTimeYear - endTimeYear);
  1319. }
  1320. int timeYear = time.Year;
  1321. if (startTimeYear != timeYear)
  1322. {
  1323. time = time.AddYears(startTimeYear - timeYear);
  1324. }
  1325. }
  1326. if (startTime > endTime)
  1327. {
  1328. // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
  1329. // Note, the summer in the southern hemisphere begins late in the year.
  1330. return time < endTime || time >= startTime;
  1331. }
  1332. else if (rule.NoDaylightTransitions)
  1333. {
  1334. // In NoDaylightTransitions AdjustmentRules, the startTime is always before the endTime,
  1335. // and both the start and end times are inclusive
  1336. return time >= startTime && time <= endTime;
  1337. }
  1338. else
  1339. {
  1340. // In northern hemisphere, the daylight saving time starts in the middle of the year.
  1341. return time >= startTime && time < endTime;
  1342. }
  1343. }
  1344. /// <summary>
  1345. /// Returns true when the dateTime falls into an ambiguous time range.
  1346. ///
  1347. /// For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from
  1348. /// 2AM to 1AM. This means the timeline on Sunday proceeds as follows:
  1349. /// 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ...
  1350. ///
  1351. /// In this example, any DateTime values that fall into the [1AM - 1:59:59AM] range
  1352. /// are ambiguous; as it is unclear if these times are in Daylight Saving Time.
  1353. /// </summary>
  1354. private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
  1355. {
  1356. bool isAmbiguous = false;
  1357. if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
  1358. {
  1359. return isAmbiguous;
  1360. }
  1361. DateTime startAmbiguousTime;
  1362. DateTime endAmbiguousTime;
  1363. // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
  1364. if (rule.DaylightDelta > TimeSpan.Zero)
  1365. {
  1366. if (rule.IsEndDateMarkerForEndOfYear())
  1367. { // year end with daylight on so there is no ambiguous time
  1368. return false;
  1369. }
  1370. startAmbiguousTime = daylightTime.End;
  1371. endAmbiguousTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
  1372. }
  1373. else
  1374. {
  1375. if (rule.IsStartDateMarkerForBeginningOfYear())
  1376. { // year start with daylight on so there is no ambiguous time
  1377. return false;
  1378. }
  1379. startAmbiguousTime = daylightTime.Start;
  1380. endAmbiguousTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */
  1381. }
  1382. isAmbiguous = (time >= endAmbiguousTime && time < startAmbiguousTime);
  1383. if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year)
  1384. {
  1385. // there exists an extreme corner case where the start or end period is on a year boundary and
  1386. // because of this the comparison above might have been performed for a year-early or a year-later
  1387. // than it should have been.
  1388. DateTime startModifiedAmbiguousTime;
  1389. DateTime endModifiedAmbiguousTime;
  1390. try
  1391. {
  1392. startModifiedAmbiguousTime = startAmbiguousTime.AddYears(1);
  1393. endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1);
  1394. isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
  1395. }
  1396. catch (ArgumentOutOfRangeException) { }
  1397. if (!isAmbiguous)
  1398. {
  1399. try
  1400. {
  1401. startModifiedAmbiguousTime = startAmbiguousTime.AddYears(-1);
  1402. endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1);
  1403. isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
  1404. }
  1405. catch (ArgumentOutOfRangeException) { }
  1406. }
  1407. }
  1408. return isAmbiguous;
  1409. }
  1410. /// <summary>
  1411. /// Helper function that checks if a given DateTime is in an invalid time ("time hole")
  1412. /// A "time hole" occurs at a DST transition point when time jumps forward;
  1413. /// For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
  1414. /// 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole".
  1415. /// A "time hole" is not limited to only occurring at the start of DST, and may occur at
  1416. /// the end of DST as well.
  1417. /// </summary>
  1418. private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
  1419. {
  1420. bool isInvalid = false;
  1421. if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
  1422. {
  1423. return isInvalid;
  1424. }
  1425. DateTime startInvalidTime;
  1426. DateTime endInvalidTime;
  1427. // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
  1428. if (rule.DaylightDelta < TimeSpan.Zero)
  1429. {
  1430. // if the year ends with daylight saving on then there cannot be any time-hole's in that year.
  1431. if (rule.IsEndDateMarkerForEndOfYear())
  1432. return false;
  1433. startInvalidTime = daylightTime.End;
  1434. endInvalidTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
  1435. }
  1436. else
  1437. {
  1438. // if the year starts with daylight saving on then there cannot be any time-hole's in that year.
  1439. if (rule.IsStartDateMarkerForBeginningOfYear())
  1440. return false;
  1441. startInvalidTime = daylightTime.Start;
  1442. endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */
  1443. }
  1444. isInvalid = (time >= startInvalidTime && time < endInvalidTime);
  1445. if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year)
  1446. {
  1447. // there exists an extreme corner case where the start or end period is on a year boundary and
  1448. // because of this the comparison above might have been performed for a year-early or a year-later
  1449. // than it should have been.
  1450. DateTime startModifiedInvalidTime;
  1451. DateTime endModifiedInvalidTime;
  1452. try
  1453. {
  1454. startModifiedInvalidTime = startInvalidTime.AddYears(1);
  1455. endModifiedInvalidTime = endInvalidTime.AddYears(1);
  1456. isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
  1457. }
  1458. catch (ArgumentOutOfRangeException) { }
  1459. if (!isInvalid)
  1460. {
  1461. try
  1462. {
  1463. startModifiedInvalidTime = startInvalidTime.AddYears(-1);
  1464. endModifiedInvalidTime = endInvalidTime.AddYears(-1);
  1465. isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
  1466. }
  1467. catch (ArgumentOutOfRangeException) { }
  1468. }
  1469. }
  1470. return isInvalid;
  1471. }
  1472. /// <summary>
  1473. /// Helper function that calculates the UTC offset for a dateTime in a timeZone.
  1474. /// This function assumes that the dateTime is already converted into the timeZone.
  1475. /// </summary>
  1476. private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone)
  1477. {
  1478. TimeSpan baseOffset = zone.BaseUtcOffset;
  1479. int? ruleIndex;
  1480. AdjustmentRule? rule = zone.GetAdjustmentRuleForTime(time, out ruleIndex);
  1481. if (rule != null)
  1482. {
  1483. baseOffset += rule.BaseUtcOffsetDelta;
  1484. if (rule.HasDaylightSaving)
  1485. {
  1486. DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule, ruleIndex);
  1487. bool isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime);
  1488. baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
  1489. }
  1490. }
  1491. return baseOffset;
  1492. }
  1493. /// <summary>
  1494. /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
  1495. /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
  1496. /// </summary>
  1497. private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone) =>
  1498. GetUtcOffsetFromUtc(time, zone, out _);
  1499. /// <summary>
  1500. /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
  1501. /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
  1502. /// </summary>
  1503. private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings) =>
  1504. GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out _);
  1505. /// <summary>
  1506. /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
  1507. /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
  1508. /// </summary>
  1509. internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst)
  1510. {
  1511. isDaylightSavings = false;
  1512. isAmbiguousLocalDst = false;
  1513. TimeSpan baseOffset = zone.BaseUtcOffset;
  1514. int year;
  1515. int? ruleIndex;
  1516. AdjustmentRule? rule;
  1517. if (time > s_maxDateOnly)
  1518. {
  1519. rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue, out ruleIndex);
  1520. year = 9999;
  1521. }
  1522. else if (time < s_minDateOnly)
  1523. {
  1524. rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue, out ruleIndex);
  1525. year = 1;
  1526. }
  1527. else
  1528. {
  1529. rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, ruleIndex: out ruleIndex);
  1530. Debug.Assert(rule == null || ruleIndex.HasValue,
  1531. "If GetAdjustmentRuleForTime returned an AdjustmentRule, ruleIndex should also be set.");
  1532. // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset,
  1533. // sometimes the year value can change if the input datetime was very close to the beginning or the end of the year. Examples of such cases:
  1534. // Libya Standard Time when used with the date 2011-12-31T23:59:59.9999999Z
  1535. // "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z
  1536. DateTime targetTime = time + baseOffset;
  1537. year = targetTime.Year;
  1538. }
  1539. if (rule != null)
  1540. {
  1541. baseOffset += rule.BaseUtcOffsetDelta;
  1542. if (rule.HasDaylightSaving)
  1543. {
  1544. isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, rule, ruleIndex, out isAmbiguousLocalDst, zone);
  1545. baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
  1546. }
  1547. }
  1548. return baseOffset;
  1549. }
  1550. /// <summary>
  1551. /// Helper function that converts a year and TransitionTime into a DateTime.
  1552. /// </summary>
  1553. internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime)
  1554. {
  1555. DateTime value;
  1556. DateTime timeOfDay = transitionTime.TimeOfDay;
  1557. if (transitionTime.IsFixedDateRule)
  1558. {
  1559. // create a DateTime from the passed in year and the properties on the transitionTime
  1560. // if the day is out of range for the month then use the last day of the month
  1561. int day = DateTime.DaysInMonth(year, transitionTime.Month);
  1562. value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,
  1563. timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
  1564. }
  1565. else
  1566. {
  1567. if (transitionTime.Week <= 4)
  1568. {
  1569. //
  1570. // Get the (transitionTime.Week)th Sunday.
  1571. //
  1572. value = new DateTime(year, transitionTime.Month, 1,
  1573. timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
  1574. int dayOfWeek = (int)value.DayOfWeek;
  1575. int delta = (int)transitionTime.DayOfWeek - dayOfWeek;
  1576. if (delta < 0)
  1577. {
  1578. delta += 7;
  1579. }
  1580. delta += 7 * (transitionTime.Week - 1);
  1581. if (delta > 0)
  1582. {
  1583. value = value.AddDays(delta);
  1584. }
  1585. }
  1586. else
  1587. {
  1588. //
  1589. // If TransitionWeek is greater than 4, we will get the last week.
  1590. //
  1591. int daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
  1592. value = new DateTime(year, transitionTime.Month, daysInMonth,
  1593. timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
  1594. // This is the day of week for the last day of the month.
  1595. int dayOfWeek = (int)value.DayOfWeek;
  1596. int delta = dayOfWeek - (int)transitionTime.DayOfWeek;
  1597. if (delta < 0)
  1598. {
  1599. delta += 7;
  1600. }
  1601. if (delta > 0)
  1602. {
  1603. value = value.AddDays(-delta);
  1604. }
  1605. }
  1606. }
  1607. return value;
  1608. }
  1609. /// <summary>
  1610. /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
  1611. ///
  1612. /// This function may return null.
  1613. ///
  1614. /// assumes cachedData lock is taken
  1615. /// </summary>
  1616. private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo? value, out Exception? e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false)
  1617. {
  1618. Debug.Assert(Monitor.IsEntered(cachedData));
  1619. TimeZoneInfoResult result = TimeZoneInfoResult.Success;
  1620. e = null;
  1621. // check the cache
  1622. if (cachedData._systemTimeZones != null)
  1623. {
  1624. if (cachedData._systemTimeZones.TryGetValue(id, out TimeZoneInfo? match))
  1625. {
  1626. if (dstDisabled && match._supportsDaylightSavingTime)
  1627. {
  1628. // we found a cache hit but we want a time zone without DST and this one has DST data
  1629. value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
  1630. }
  1631. else
  1632. {
  1633. value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
  1634. match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
  1635. }
  1636. return result;
  1637. }
  1638. }
  1639. // Fall back to reading from the local machine when the cache is not fully populated.
  1640. // On UNIX, there may be some tzfiles that aren't in the zones.tab file, and thus aren't returned from GetSystemTimeZones().
  1641. // If a caller asks for one of these zones before calling GetSystemTimeZones(), the time zone is returned successfully. But if
  1642. // GetSystemTimeZones() is called first, FindSystemTimeZoneById will throw TimeZoneNotFoundException, which is inconsistent.
  1643. // To fix this, when 'alwaysFallbackToLocalMachine' is true, even if _allSystemTimeZonesRead is true, try reading the tzfile
  1644. // from disk, but don't add the time zone to the list returned from GetSystemTimeZones(). These time zones will only be
  1645. // available if asked for directly.
  1646. if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine)
  1647. {
  1648. result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData);
  1649. }
  1650. else
  1651. {
  1652. result = TimeZoneInfoResult.TimeZoneNotFoundException;
  1653. value = null;
  1654. }
  1655. return result;
  1656. }
  1657. private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool dstDisabled, out TimeZoneInfo? value, out Exception? e, CachedData cachedData)
  1658. {
  1659. TimeZoneInfoResult result;
  1660. TimeZoneInfo? match;
  1661. result = TryGetTimeZoneFromLocalMachine(id, out match, out e);
  1662. if (result == TimeZoneInfoResult.Success)
  1663. {
  1664. cachedData._systemTimeZones ??= new Dictionary<string, TimeZoneInfo>(StringComparer.OrdinalIgnoreCase)
  1665. {
  1666. { UtcId, s_utcTimeZone }
  1667. };
  1668. // Avoid using multiple Utc objects to ensure consistency and correctness as we have some code
  1669. // uses reference equality with the Utc object.
  1670. if (!id.Equals(UtcId, StringComparison.OrdinalIgnoreCase))
  1671. {
  1672. cachedData._systemTimeZones.Add(id, match!);
  1673. }
  1674. if (dstDisabled && match!._supportsDaylightSavingTime)
  1675. {
  1676. // we found a cache hit but we want a time zone without DST and this one has DST data
  1677. value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
  1678. }
  1679. else
  1680. {
  1681. value = new TimeZoneInfo(match!._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
  1682. match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
  1683. }
  1684. }
  1685. else
  1686. {
  1687. value = null;
  1688. }
  1689. return result;
  1690. }
  1691. /// <summary>
  1692. /// Helper function that performs all of the validation checks for the
  1693. /// factory methods and deserialization callback.
  1694. /// </summary>
  1695. private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[]? adjustmentRules, out bool adjustmentRulesSupportDst)
  1696. {
  1697. if (id == null)
  1698. {
  1699. throw new ArgumentNullException(nameof(id));
  1700. }
  1701. if (id.Length == 0)
  1702. {
  1703. throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id));
  1704. }
  1705. if (UtcOffsetOutOfRange(baseUtcOffset))
  1706. {
  1707. throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), SR.ArgumentOutOfRange_UtcOffset);
  1708. }
  1709. if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  1710. {
  1711. throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset));
  1712. }
  1713. adjustmentRulesSupportDst = false;
  1714. //
  1715. // "adjustmentRules" can either be null or a valid array of AdjustmentRule objects.
  1716. // A valid array is one that does not contain any null elements and all elements
  1717. // are sorted in chronological order
  1718. //
  1719. if (adjustmentRules != null && adjustmentRules.Length != 0)
  1720. {
  1721. adjustmentRulesSupportDst = true;
  1722. AdjustmentRule? prev = null;
  1723. AdjustmentRule? current = null;
  1724. for (int i = 0; i < adjustmentRules.Length; i++)
  1725. {
  1726. prev = current;
  1727. current = adjustmentRules[i];
  1728. if (current == null)
  1729. {
  1730. throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls);
  1731. }
  1732. if (!IsValidAdjustmentRuleOffest(baseUtcOffset, current))
  1733. {
  1734. throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta);
  1735. }
  1736. if (prev != null && current.DateStart <= prev.DateEnd)
  1737. {
  1738. // verify the rules are in chronological order and the DateStart/DateEnd do not overlap
  1739. throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder);
  1740. }
  1741. }
  1742. }
  1743. }
  1744. private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0);
  1745. private static readonly TimeSpan MinOffset = -MaxOffset;
  1746. /// <summary>
  1747. /// Helper function that validates the TimeSpan is within +/- 14.0 hours
  1748. /// </summary>
  1749. internal static bool UtcOffsetOutOfRange(TimeSpan offset) =>
  1750. offset < MinOffset || offset > MaxOffset;
  1751. private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)
  1752. {
  1753. return baseUtcOffset
  1754. + adjustmentRule.BaseUtcOffsetDelta
  1755. + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero);
  1756. }
  1757. /// <summary>
  1758. /// Helper function that performs adjustment rule validation
  1759. /// </summary>
  1760. private static bool IsValidAdjustmentRuleOffest(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)
  1761. {
  1762. TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);
  1763. return !UtcOffsetOutOfRange(utcOffset);
  1764. }
  1765. }
  1766. }