TimeZoneInfo.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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.adjustmentRules == null) != (other.adjustmentRules == null))
  343. return false;
  344. if (this.adjustmentRules == null)
  345. return true;
  346. if (this.BaseUtcOffset != other.BaseUtcOffset)
  347. return false;
  348. if (this.adjustmentRules.Length != other.adjustmentRules.Length)
  349. return false;
  350. for (int i = 0; i < adjustmentRules.Length; i++) {
  351. if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
  352. return false;
  353. }
  354. return true;
  355. }
  356. public bool IsAmbiguousTime (DateTime dateTime)
  357. {
  358. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  359. throw new ArgumentException ("Kind is Local and time is Invalid");
  360. if (this == TimeZoneInfo.Utc)
  361. return false;
  362. if (dateTime.Kind == DateTimeKind.Utc)
  363. dateTime = ConvertTimeFromUtc (dateTime);
  364. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  365. dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
  366. AdjustmentRule rule = GetApplicableRule (dateTime);
  367. DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
  368. if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
  369. return true;
  370. return false;
  371. }
  372. public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
  373. {
  374. throw new NotImplementedException ();
  375. }
  376. public bool IsDaylightSavingTime (DateTime dateTime)
  377. {
  378. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  379. throw new ArgumentException ("dateTime is invalid and Kind is Local");
  380. if (this == TimeZoneInfo.Utc)
  381. return false;
  382. if (!SupportsDaylightSavingTime)
  383. return false;
  384. //FIXME: do not rely on DateTime implementation !
  385. if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
  386. return dateTime.IsDaylightSavingTime ();
  387. //FIXME: do not rely on DateTime implementation !
  388. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
  389. return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
  390. AdjustmentRule rule = GetApplicableRule (dateTime.Date);
  391. if (rule == null)
  392. return false;
  393. DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  394. DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
  395. if (dateTime.Kind == DateTimeKind.Utc) {
  396. DST_start -= BaseUtcOffset;
  397. DST_end -= (BaseUtcOffset + rule.DaylightDelta);
  398. }
  399. return (dateTime >= DST_start && dateTime < DST_end);
  400. }
  401. public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
  402. {
  403. throw new NotImplementedException ();
  404. }
  405. public bool IsInvalidTime (DateTime dateTime)
  406. {
  407. if (dateTime.Kind == DateTimeKind.Utc)
  408. return false;
  409. if (dateTime.Kind == DateTimeKind.Local && this != Local)
  410. return false;
  411. AdjustmentRule rule = GetApplicableRule (dateTime);
  412. DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  413. if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
  414. return true;
  415. return false;
  416. }
  417. public void OnDeserialization (object sender)
  418. {
  419. throw new NotImplementedException ();
  420. }
  421. public string ToSerializedString ()
  422. {
  423. throw new NotImplementedException ();
  424. }
  425. public override string ToString ()
  426. {
  427. return DisplayName;
  428. }
  429. private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  430. {
  431. if (id == null)
  432. throw new ArgumentNullException ("id");
  433. if (id == String.Empty)
  434. throw new ArgumentException ("id parameter is an empty string");
  435. if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  436. throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
  437. if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
  438. throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
  439. #if STRICT
  440. if (id.Length > 32)
  441. throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
  442. #endif
  443. if (adjustmentRules != null && adjustmentRules.Length != 0) {
  444. AdjustmentRule prev = null;
  445. foreach (AdjustmentRule current in adjustmentRules) {
  446. if (current == null)
  447. throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
  448. if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
  449. (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
  450. 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;");
  451. if (prev != null && prev.DateStart > current.DateStart)
  452. throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
  453. if (prev != null && prev.DateEnd > current.DateStart)
  454. throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
  455. if (prev != null && prev.DateEnd == current.DateStart)
  456. throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
  457. prev = current;
  458. }
  459. }
  460. this.id = id;
  461. this.baseUtcOffset = baseUtcOffset;
  462. this.displayName = displayName ?? id;
  463. this.standardDisplayName = standardDisplayName ?? id;
  464. this.daylightDisplayName = daylightDisplayName;
  465. this.disableDaylightSavingTime = disableDaylightSavingTime;
  466. this.adjustmentRules = adjustmentRules;
  467. }
  468. private AdjustmentRule GetApplicableRule (DateTime dateTime)
  469. {
  470. //Transitions are always in standard time
  471. DateTime date = dateTime;
  472. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  473. date = date.ToUniversalTime () + BaseUtcOffset;
  474. if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
  475. date = date + BaseUtcOffset;
  476. foreach (AdjustmentRule rule in adjustmentRules) {
  477. if (rule.DateStart > date.Date)
  478. return null;
  479. if (rule.DateEnd < date.Date)
  480. continue;
  481. return rule;
  482. }
  483. return null;
  484. }
  485. private static DateTime TransitionPoint (TransitionTime transition, int year)
  486. {
  487. if (transition.IsFixedDateRule)
  488. return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
  489. DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
  490. int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
  491. if (day > DateTime.DaysInMonth (year, transition.Month))
  492. day -= 7;
  493. return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
  494. }
  495. #if LIBC
  496. private static bool ValidTZFile (byte [] buffer, int length)
  497. {
  498. StringBuilder magic = new StringBuilder ();
  499. for (int i = 0; i < 4; i++)
  500. magic.Append ((char)buffer [i]);
  501. if (magic.ToString () != "TZif")
  502. return false;
  503. if (length >= BUFFER_SIZE)
  504. return false;
  505. return true;
  506. }
  507. struct TimeType
  508. {
  509. public readonly int Offset;
  510. public readonly bool IsDst;
  511. public string Name;
  512. public TimeType (int offset, bool is_dst, string abbrev)
  513. {
  514. this.Offset = offset;
  515. this.IsDst = is_dst;
  516. this.Name = abbrev;
  517. }
  518. public override string ToString ()
  519. {
  520. return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
  521. }
  522. }
  523. private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
  524. {
  525. DataConverter enc = DataConverter.BigEndian;
  526. //Reading the header. 4 bytes for magic, 16 are reserved
  527. int ttisgmtcnt = enc.GetInt32 (buffer, 20);
  528. int ttisstdcnt = enc.GetInt32 (buffer, 24);
  529. int leapcnt = enc.GetInt32 (buffer, 28);
  530. int timecnt = enc.GetInt32 (buffer, 32);
  531. int typecnt = enc.GetInt32 (buffer, 36);
  532. int charcnt = enc.GetInt32 (buffer, 40);
  533. if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
  534. throw new InvalidTimeZoneException ();
  535. Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
  536. Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
  537. SortedList<DateTime, TimeType> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
  538. if (time_types.Count == 0)
  539. throw new InvalidTimeZoneException ();
  540. if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
  541. throw new InvalidTimeZoneException ();
  542. TimeSpan baseUtcOffset = new TimeSpan (0);
  543. TimeSpan dstDelta = new TimeSpan (0);
  544. string standardDisplayName = null;
  545. string daylightDisplayName = null;
  546. bool dst_observed = false;
  547. DateTime dst_start = DateTime.MinValue;
  548. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  549. for (int i = 0; i < transitions.Count; i++) {
  550. DateTime ttime = transitions.Keys [i];
  551. TimeType ttype = transitions [ttime];
  552. if (!ttype.IsDst) {
  553. if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
  554. standardDisplayName = ttype.Name;
  555. daylightDisplayName = null;
  556. baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
  557. adjustmentRules = new List<AdjustmentRule> ();
  558. dst_observed = false;
  559. }
  560. if (dst_observed) {
  561. //FIXME: check additional fields for this:
  562. //most of the transitions are expressed in GMT
  563. dst_start += baseUtcOffset;
  564. DateTime dst_end = ttime + baseUtcOffset + dstDelta;
  565. //some weird timezone (America/Phoenix) have end dates on Jan 1st
  566. if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
  567. dst_end -= new TimeSpan (24, 0, 0);
  568. DateTime dateStart, dateEnd;
  569. if (dst_start.Month < 7)
  570. dateStart = new DateTime (dst_start.Year, 1, 1);
  571. else
  572. dateStart = new DateTime (dst_start.Year, 7, 1);
  573. if (dst_end.Month >= 7)
  574. dateEnd = new DateTime (dst_end.Year, 12, 31);
  575. else
  576. dateEnd = new DateTime (dst_end.Year, 6, 30);
  577. TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
  578. TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
  579. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
  580. }
  581. dst_observed = false;
  582. } else {
  583. if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
  584. daylightDisplayName = ttype.Name;
  585. dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
  586. }
  587. dst_start = ttime;
  588. dst_observed = true;
  589. }
  590. }
  591. if (adjustmentRules.Count == 0) {
  592. TimeType t = (TimeType)time_types [0];
  593. if (standardDisplayName == null) {
  594. standardDisplayName = t.Name;
  595. baseUtcOffset = new TimeSpan (0, 0, t.Offset);
  596. }
  597. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
  598. } else {
  599. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, adjustmentRules.ToArray ());
  600. }
  601. }
  602. static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
  603. {
  604. var abbrevs = new Dictionary<int, string> ();
  605. int abbrev_index = 0;
  606. var sb = new StringBuilder ();
  607. for (int i = 0; i < count; i++) {
  608. char c = (char) buffer [index + i];
  609. if (c != '\0')
  610. sb.Append (c);
  611. else {
  612. abbrevs.Add (abbrev_index, sb.ToString ());
  613. abbrev_index = i + 1;
  614. sb = new StringBuilder ();
  615. }
  616. }
  617. return abbrevs;
  618. }
  619. static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
  620. {
  621. DataConverter enc = DataConverter.BigEndian;
  622. var types = new Dictionary<int, TimeType> (count);
  623. for (int i = 0; i < count; i++) {
  624. int offset = enc.GetInt32 (buffer, index + 6 * i);
  625. byte is_dst = buffer [index + 6 * i + 4];
  626. byte abbrev = buffer [index + 6 * i + 5];
  627. types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
  628. }
  629. return types;
  630. }
  631. static SortedList<DateTime, TimeType> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
  632. {
  633. DataConverter enc = DataConverter.BigEndian;
  634. var trans = new SortedList<DateTime, TimeType> (count);
  635. for (int i = 0; i < count; i++) {
  636. int unixtime = enc.GetInt32 (buffer, index + 4 * i);
  637. DateTime ttime = DateTimeFromUnixTime (unixtime);
  638. byte ttype = buffer [index + 4 * count + i];
  639. trans.Add (ttime, time_types [(int)ttype]);
  640. }
  641. return trans;
  642. }
  643. static DateTime DateTimeFromUnixTime (long unix_time)
  644. {
  645. DateTime date_time = new DateTime (1970, 1, 1);
  646. return date_time.AddSeconds (unix_time);
  647. }
  648. #endif
  649. }
  650. }