TimeZoneInfo.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. /*
  2. * System.TimeZoneInfo
  3. *
  4. * Author(s)
  5. * Stephane Delcroix <[email protected]>
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining
  8. * a copy of this software and associated documentation files (the
  9. * "Software"), to deal in the Software without restriction, including
  10. * without limitation the rights to use, copy, modify, merge, publish,
  11. * distribute, sublicense, and/or sell copies of the Software, and to
  12. * permit persons to whom the Software is furnished to do so, subject to
  13. * the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be
  16. * included in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. */
  26. using System.Collections.Generic;
  27. using System.Collections.ObjectModel;
  28. using System.Runtime.Serialization;
  29. using System.Text;
  30. #if LIBC
  31. using System.IO;
  32. using Mono;
  33. #endif
  34. namespace System
  35. {
  36. [SerializableAttribute]
  37. public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
  38. {
  39. TimeSpan baseUtcOffset;
  40. public TimeSpan BaseUtcOffset {
  41. get { return baseUtcOffset; }
  42. }
  43. string daylightDisplayName;
  44. public string DaylightName {
  45. get {
  46. if (disableDaylightSavingTime)
  47. return String.Empty;
  48. return daylightDisplayName;
  49. }
  50. }
  51. string displayName;
  52. public string DisplayName {
  53. get { return displayName; }
  54. }
  55. string id;
  56. public string Id {
  57. get { return id; }
  58. }
  59. static TimeZoneInfo local;
  60. public static TimeZoneInfo Local {
  61. get {
  62. if (local == null) {
  63. #if LIBC
  64. try {
  65. local = FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
  66. } catch {
  67. try {
  68. local = FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
  69. } catch {
  70. throw new TimeZoneNotFoundException ();
  71. }
  72. }
  73. #else
  74. throw new TimeZoneNotFoundException ();
  75. #endif
  76. }
  77. return local;
  78. }
  79. }
  80. string standardDisplayName;
  81. public string StandardName {
  82. get { return standardDisplayName; }
  83. }
  84. bool disableDaylightSavingTime;
  85. public bool SupportsDaylightSavingTime {
  86. get { return !disableDaylightSavingTime; }
  87. }
  88. static TimeZoneInfo utc;
  89. public static TimeZoneInfo Utc {
  90. get {
  91. if (utc == null)
  92. utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
  93. return utc;
  94. }
  95. }
  96. #if LIBC
  97. static string timeZoneDirectory = null;
  98. public static string TimeZoneDirectory {
  99. get {
  100. if (timeZoneDirectory == null)
  101. timeZoneDirectory = "/usr/share/zoneinfo";
  102. return timeZoneDirectory;
  103. }
  104. set {
  105. ClearCachedData ();
  106. timeZoneDirectory = value;
  107. }
  108. }
  109. #endif
  110. private AdjustmentRule [] adjustmentRules;
  111. public static void ClearCachedData ()
  112. {
  113. local = null;
  114. utc = null;
  115. systemTimeZones = null;
  116. }
  117. public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
  118. {
  119. return ConvertTime (dateTime, TimeZoneInfo.Local, destinationTimeZone);
  120. }
  121. public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
  122. {
  123. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
  124. throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
  125. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
  126. throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
  127. if (sourceTimeZone.IsInvalidTime (dateTime))
  128. throw new ArgumentException ("dateTime parameter is an invalid time");
  129. if (sourceTimeZone == null)
  130. throw new ArgumentNullException ("sourceTimeZone");
  131. if (destinationTimeZone == null)
  132. throw new ArgumentNullException ("destinationTimeZone");
  133. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
  134. return dateTime;
  135. DateTime utc = ConvertTimeToUtc (dateTime);
  136. if (destinationTimeZone == TimeZoneInfo.Utc)
  137. return utc;
  138. return ConvertTimeFromUtc (utc, destinationTimeZone);
  139. }
  140. public static DateTimeOffset ConvertTime (DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
  141. {
  142. throw new NotImplementedException ();
  143. }
  144. public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
  145. {
  146. return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
  147. }
  148. public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
  149. {
  150. return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
  151. }
  152. public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
  153. {
  154. return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
  155. }
  156. private DateTime ConvertTimeFromUtc (DateTime dateTime)
  157. {
  158. if (dateTime.Kind == DateTimeKind.Local)
  159. throw new ArgumentException ("Kind property of dateTime is Local");
  160. if (this == TimeZoneInfo.Utc)
  161. return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
  162. //FIXME: do not rely on DateTime implementation !
  163. if (this == TimeZoneInfo.Local)
  164. return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
  165. AdjustmentRule rule = GetApplicableRule (dateTime);
  166. if (IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
  167. return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
  168. else
  169. return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
  170. }
  171. public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
  172. {
  173. if (destinationTimeZone == null)
  174. throw new ArgumentNullException ("destinationTimeZone");
  175. return destinationTimeZone.ConvertTimeFromUtc (dateTime);
  176. }
  177. public static DateTime ConvertTimeToUtc (DateTime dateTime)
  178. {
  179. if (dateTime.Kind == DateTimeKind.Utc)
  180. return dateTime;
  181. //FIXME: do not rely on DateTime implementation !
  182. return DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc);
  183. }
  184. public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
  185. {
  186. if (sourceTimeZone == null)
  187. throw new ArgumentNullException ("sourceTimeZone");
  188. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
  189. throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
  190. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
  191. throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
  192. if (sourceTimeZone.IsInvalidTime (dateTime))
  193. throw new ArgumentException ("dateTime parameter is an invalid time");
  194. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone == TimeZoneInfo.Utc)
  195. return dateTime;
  196. if (dateTime.Kind == DateTimeKind.Utc)
  197. return dateTime;
  198. if (dateTime.Kind == DateTimeKind.Local)
  199. return ConvertTimeToUtc (dateTime);
  200. if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
  201. return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
  202. else {
  203. AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
  204. return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
  205. }
  206. }
  207. public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
  208. {
  209. return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
  210. }
  211. public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
  212. {
  213. return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
  214. }
  215. public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  216. {
  217. return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
  218. }
  219. public bool Equals (TimeZoneInfo other)
  220. {
  221. if (other == null)
  222. return false;
  223. return other.Id == this.Id && HasSameRules (other);
  224. }
  225. public static TimeZoneInfo FindSystemTimeZoneById (string id)
  226. {
  227. //FIXME: this method should check for cached values in systemTimeZones
  228. if (id == null)
  229. throw new ArgumentNullException ("id");
  230. #if LIBC
  231. string filepath = Path.Combine (TimeZoneDirectory, id);
  232. return FindSystemTimeZoneByFileName (id, filepath);
  233. #else
  234. throw new NotImplementedException ();
  235. #endif
  236. }
  237. #if LIBC
  238. const int BUFFER_SIZE = 8192; //Big enough for any tz file
  239. private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
  240. {
  241. if (!File.Exists (filepath))
  242. throw new TimeZoneNotFoundException ();
  243. byte [] buffer = new byte [BUFFER_SIZE];
  244. int length;
  245. using (FileStream stream = File.OpenRead (filepath)) {
  246. length = stream.Read (buffer, 0, BUFFER_SIZE);
  247. }
  248. if (!ValidTZFile (buffer, length))
  249. throw new InvalidTimeZoneException ();
  250. try {
  251. return ParseTZBuffer (id, buffer, length);
  252. } catch (Exception e) {
  253. throw new InvalidTimeZoneException (e.Message);
  254. }
  255. }
  256. #endif
  257. public static TimeZoneInfo FromSerializedString (string source)
  258. {
  259. throw new NotImplementedException ();
  260. }
  261. public AdjustmentRule [] GetAdjustmentRules ()
  262. {
  263. if (disableDaylightSavingTime)
  264. return new AdjustmentRule [0];
  265. else
  266. return (AdjustmentRule []) adjustmentRules.Clone ();
  267. }
  268. public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
  269. {
  270. if (!IsAmbiguousTime (dateTime))
  271. throw new ArgumentException ("dateTime is not an ambiguous time");
  272. AdjustmentRule rule = GetApplicableRule (dateTime);
  273. return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
  274. }
  275. public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
  276. {
  277. if (!IsAmbiguousTime (dateTimeOffset))
  278. throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
  279. throw new NotImplementedException ();
  280. }
  281. public override int GetHashCode ()
  282. {
  283. int hash_code = Id.GetHashCode ();
  284. foreach (AdjustmentRule rule in GetAdjustmentRules ())
  285. hash_code ^= rule.GetHashCode ();
  286. return hash_code;
  287. }
  288. public void GetObjectData (SerializationInfo info, StreamingContext context)
  289. {
  290. throw new NotImplementedException ();
  291. }
  292. //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
  293. private static List<TimeZoneInfo> systemTimeZones = null;
  294. public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
  295. {
  296. if (systemTimeZones == null) {
  297. systemTimeZones = new List<TimeZoneInfo> ();
  298. #if LIBC
  299. string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
  300. foreach (string continent in continents) {
  301. try {
  302. foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
  303. try {
  304. string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
  305. systemTimeZones.Add (FindSystemTimeZoneById (id));
  306. } catch (ArgumentNullException) {
  307. } catch (TimeZoneNotFoundException) {
  308. } catch (InvalidTimeZoneException) {
  309. } catch (Exception e) {
  310. if (e is OutOfMemoryException || e is System.Security.SecurityException)
  311. throw;
  312. else {
  313. Console.WriteLine ("Unexpected Exception");
  314. throw;
  315. }
  316. }
  317. }
  318. } catch {}
  319. }
  320. #else
  321. throw new NotImplementedException ("This method is not implemented for this platform");
  322. #endif
  323. }
  324. return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
  325. }
  326. public TimeSpan GetUtcOffset (DateTime dateTime)
  327. {
  328. if (IsDaylightSavingTime (dateTime)) {
  329. AdjustmentRule rule = GetApplicableRule (dateTime);
  330. return BaseUtcOffset + rule.DaylightDelta;
  331. }
  332. return BaseUtcOffset;
  333. }
  334. public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
  335. {
  336. throw new NotImplementedException ();
  337. }
  338. public bool HasSameRules (TimeZoneInfo other)
  339. {
  340. if (other == null)
  341. throw new ArgumentNullException ("other");
  342. if (this.BaseUtcOffset != other.BaseUtcOffset)
  343. return false;
  344. if (this.adjustmentRules.Length != other.adjustmentRules.Length)
  345. return false;
  346. for (int i = 0; i < adjustmentRules.Length; i++) {
  347. if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
  348. return false;
  349. }
  350. return true;
  351. }
  352. public bool IsAmbiguousTime (DateTime dateTime)
  353. {
  354. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  355. throw new ArgumentException ("Kind is Local and time is Invalid");
  356. if (this == TimeZoneInfo.Utc)
  357. return false;
  358. if (dateTime.Kind == DateTimeKind.Utc)
  359. dateTime = ConvertTimeFromUtc (dateTime);
  360. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  361. dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
  362. AdjustmentRule rule = GetApplicableRule (dateTime);
  363. DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
  364. if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
  365. return true;
  366. return false;
  367. }
  368. public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
  369. {
  370. throw new NotImplementedException ();
  371. }
  372. public bool IsDaylightSavingTime (DateTime dateTime)
  373. {
  374. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  375. throw new ArgumentException ("dateTime is invalid and Kind is Local");
  376. if (this == TimeZoneInfo.Utc)
  377. return false;
  378. if (!SupportsDaylightSavingTime)
  379. return false;
  380. //FIXME: do not rely on DateTime implementation !
  381. if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
  382. return dateTime.IsDaylightSavingTime ();
  383. //FIXME: do not rely on DateTime implementation !
  384. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
  385. return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
  386. AdjustmentRule rule = GetApplicableRule (dateTime.Date);
  387. if (rule == null)
  388. return false;
  389. DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  390. DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
  391. if (dateTime.Kind == DateTimeKind.Utc) {
  392. DST_start -= BaseUtcOffset;
  393. DST_end -= (BaseUtcOffset + rule.DaylightDelta);
  394. }
  395. return (dateTime >= DST_start && dateTime < DST_end);
  396. }
  397. public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
  398. {
  399. throw new NotImplementedException ();
  400. }
  401. public bool IsInvalidTime (DateTime dateTime)
  402. {
  403. if (dateTime.Kind == DateTimeKind.Utc)
  404. return false;
  405. if (dateTime.Kind == DateTimeKind.Local && this != Local)
  406. return false;
  407. AdjustmentRule rule = GetApplicableRule (dateTime);
  408. DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  409. if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
  410. return true;
  411. return false;
  412. }
  413. public void OnDeserialization (object sender)
  414. {
  415. throw new NotImplementedException ();
  416. }
  417. public string ToSerializedString ()
  418. {
  419. throw new NotImplementedException ();
  420. }
  421. public override string ToString ()
  422. {
  423. return DisplayName;
  424. }
  425. private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  426. {
  427. if (id == null)
  428. throw new ArgumentNullException ("id");
  429. if (id == String.Empty)
  430. throw new ArgumentException ("id parameter is an empty string");
  431. if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  432. throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
  433. if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
  434. throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
  435. #if STRICT
  436. if (id.Length > 32)
  437. throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
  438. #endif
  439. if (adjustmentRules != null && adjustmentRules.Length != 0) {
  440. AdjustmentRule prev = null;
  441. foreach (AdjustmentRule current in adjustmentRules) {
  442. if (current == null)
  443. throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
  444. if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
  445. (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
  446. throw new InvalidTimeZoneException ("Sum of baseUtcOffset and DaylightDelta of one or more object in adjustmentRules array is greater than 14 or less than -14 hours;");
  447. if (prev != null && prev.DateStart > current.DateStart)
  448. throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
  449. if (prev != null && prev.DateEnd > current.DateStart)
  450. throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
  451. if (prev != null && prev.DateEnd == current.DateStart)
  452. throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
  453. prev = current;
  454. }
  455. }
  456. this.id = id;
  457. this.baseUtcOffset = baseUtcOffset;
  458. this.displayName = displayName ?? id;
  459. this.standardDisplayName = standardDisplayName ?? id;
  460. this.daylightDisplayName = daylightDisplayName;
  461. this.disableDaylightSavingTime = disableDaylightSavingTime;
  462. this.adjustmentRules = adjustmentRules;
  463. }
  464. private AdjustmentRule GetApplicableRule (DateTime dateTime)
  465. {
  466. //Transitions are always in standard time
  467. DateTime date = dateTime;
  468. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  469. date = date.ToUniversalTime () + BaseUtcOffset;
  470. if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
  471. date = date + BaseUtcOffset;
  472. foreach (AdjustmentRule rule in adjustmentRules) {
  473. if (rule.DateStart > date.Date)
  474. return null;
  475. if (rule.DateEnd < date.Date)
  476. continue;
  477. return rule;
  478. }
  479. return null;
  480. }
  481. private static DateTime TransitionPoint (TransitionTime transition, int year)
  482. {
  483. if (transition.IsFixedDateRule)
  484. return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
  485. DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
  486. int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
  487. if (day > DateTime.DaysInMonth (year, transition.Month))
  488. day -= 7;
  489. return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
  490. }
  491. #if LIBC
  492. private static bool ValidTZFile (byte [] buffer, int length)
  493. {
  494. StringBuilder magic = new StringBuilder ();
  495. for (int i = 0; i < 4; i++)
  496. magic.Append ((char)buffer [i]);
  497. if (magic.ToString () != "TZif")
  498. return false;
  499. if (length >= BUFFER_SIZE)
  500. return false;
  501. return true;
  502. }
  503. struct TimeType
  504. {
  505. public readonly int Offset;
  506. public readonly bool IsDst;
  507. public string Name;
  508. public TimeType (int offset, bool is_dst, string abbrev)
  509. {
  510. this.Offset = offset;
  511. this.IsDst = is_dst;
  512. this.Name = abbrev;
  513. }
  514. public override string ToString ()
  515. {
  516. return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
  517. }
  518. }
  519. private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
  520. {
  521. DataConverter enc = DataConverter.BigEndian;
  522. //Reading the header. 4 bytes for magic, 16 are reserved
  523. int ttisgmtcnt = enc.GetInt32 (buffer, 20);
  524. int ttisstdcnt = enc.GetInt32 (buffer, 24);
  525. int leapcnt = enc.GetInt32 (buffer, 28);
  526. int timecnt = enc.GetInt32 (buffer, 32);
  527. int typecnt = enc.GetInt32 (buffer, 36);
  528. int charcnt = enc.GetInt32 (buffer, 40);
  529. if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
  530. throw new InvalidTimeZoneException ();
  531. Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
  532. Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
  533. SortedList<DateTime, TimeType> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
  534. if (time_types.Count == 0)
  535. throw new InvalidTimeZoneException ();
  536. if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
  537. throw new InvalidTimeZoneException ();
  538. TimeSpan baseUtcOffset = new TimeSpan (0);
  539. TimeSpan dstDelta = new TimeSpan (0);
  540. string standardDisplayName = null;
  541. string daylightDisplayName = null;
  542. bool dst_observed = false;
  543. DateTime dst_start = DateTime.MinValue;
  544. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  545. for (int i = 0; i < transitions.Count; i++) {
  546. DateTime ttime = transitions.Keys [i];
  547. TimeType ttype = transitions [ttime];
  548. if (!ttype.IsDst) {
  549. if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
  550. standardDisplayName = ttype.Name;
  551. daylightDisplayName = null;
  552. baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
  553. adjustmentRules = new List<AdjustmentRule> ();
  554. dst_observed = false;
  555. }
  556. if (dst_observed) {
  557. //FIXME: check additional fields for this:
  558. //most of the transitions are expressed in GMT
  559. dst_start += baseUtcOffset;
  560. DateTime dst_end = ttime + baseUtcOffset + dstDelta;
  561. DateTime dateStart, dateEnd;
  562. if (dst_start.Month < 7)
  563. dateStart = new DateTime (dst_start.Year, 1, 1);
  564. else
  565. dateStart = new DateTime (dst_start.Year, 7, 1);
  566. if (dst_end.Month >= 7)
  567. dateEnd = new DateTime (dst_start.Year, 12, 31);
  568. else
  569. dateEnd = new DateTime (dst_end.Year, 6, 30);
  570. TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
  571. TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
  572. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
  573. }
  574. dst_observed = false;
  575. } else {
  576. if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
  577. daylightDisplayName = ttype.Name;
  578. dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
  579. }
  580. dst_start = ttime;
  581. dst_observed = true;
  582. }
  583. }
  584. if (adjustmentRules.Count == 0) {
  585. TimeType t = (TimeType)time_types [0];
  586. if (standardDisplayName == null) {
  587. standardDisplayName = t.Name;
  588. baseUtcOffset = new TimeSpan (0, 0, t.Offset);
  589. }
  590. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
  591. } else {
  592. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, adjustmentRules.ToArray ());
  593. }
  594. }
  595. static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
  596. {
  597. var abbrevs = new Dictionary<int, string> ();
  598. int abbrev_index = 0;
  599. var sb = new StringBuilder ();
  600. for (int i = 0; i < count; i++) {
  601. char c = (char) buffer [index + i];
  602. if (c != '\0')
  603. sb.Append (c);
  604. else {
  605. abbrevs.Add (abbrev_index, sb.ToString ());
  606. abbrev_index = i + 1;
  607. sb = new StringBuilder ();
  608. }
  609. }
  610. return abbrevs;
  611. }
  612. static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
  613. {
  614. DataConverter enc = DataConverter.BigEndian;
  615. var types = new Dictionary<int, TimeType> (count);
  616. for (int i = 0; i < count; i++) {
  617. int offset = enc.GetInt32 (buffer, index + 6 * i);
  618. byte is_dst = buffer [index + 6 * i + 4];
  619. byte abbrev = buffer [index + 6 * i + 5];
  620. types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
  621. }
  622. return types;
  623. }
  624. static SortedList<DateTime, TimeType> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
  625. {
  626. DataConverter enc = DataConverter.BigEndian;
  627. var trans = new SortedList<DateTime, TimeType> (count);
  628. for (int i = 0; i < count; i++) {
  629. int unixtime = enc.GetInt32 (buffer, index + 4 * i);
  630. DateTime ttime = DateTimeFromUnixTime (unixtime);
  631. byte ttype = buffer [index + 4 * count + i];
  632. trans.Add (ttime, time_types [(int)ttype]);
  633. }
  634. return trans;
  635. }
  636. static DateTime DateTimeFromUnixTime (long unix_time)
  637. {
  638. DateTime date_time = new DateTime (1970, 1, 1);
  639. return date_time.AddSeconds (unix_time);
  640. }
  641. #endif
  642. }
  643. }