TimeZoneInfo.cs 91 KB

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