TimeZoneInfo.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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;
  27. using System.Runtime.CompilerServices;
  28. #if !INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT)
  29. [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
  30. #elif NET_3_5 || (MONOTOUCH && !INSIDE_CORLIB) || (MOONLIGHT && INSIDE_CORLIB)
  31. using System.Collections.Generic;
  32. using System.Collections.ObjectModel;
  33. using System.Runtime.Serialization;
  34. using System.Text;
  35. #if LIBC
  36. using System.IO;
  37. using Mono;
  38. #endif
  39. using Microsoft.Win32;
  40. namespace System
  41. {
  42. #if NET_4_0 || BOOTSTRAP_NET_4_0
  43. [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
  44. #elif MOONLIGHT
  45. [TypeForwardedFrom (Consts.AssemblySystem_Core)]
  46. #endif
  47. [SerializableAttribute]
  48. public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
  49. {
  50. TimeSpan baseUtcOffset;
  51. public TimeSpan BaseUtcOffset {
  52. get { return baseUtcOffset; }
  53. }
  54. string daylightDisplayName;
  55. public string DaylightName {
  56. get {
  57. if (disableDaylightSavingTime)
  58. return String.Empty;
  59. return daylightDisplayName;
  60. }
  61. }
  62. string displayName;
  63. public string DisplayName {
  64. get { return displayName; }
  65. }
  66. string id;
  67. public string Id {
  68. get { return id; }
  69. }
  70. static TimeZoneInfo local;
  71. public static TimeZoneInfo Local {
  72. get {
  73. if (local == null) {
  74. #if LIBC
  75. try {
  76. local = FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
  77. } catch {
  78. try {
  79. local = FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
  80. } catch {
  81. throw new TimeZoneNotFoundException ();
  82. }
  83. }
  84. #else
  85. throw new TimeZoneNotFoundException ();
  86. #endif
  87. }
  88. return local;
  89. }
  90. }
  91. string standardDisplayName;
  92. public string StandardName {
  93. get { return standardDisplayName; }
  94. }
  95. bool disableDaylightSavingTime;
  96. public bool SupportsDaylightSavingTime {
  97. get { return !disableDaylightSavingTime; }
  98. }
  99. static TimeZoneInfo utc;
  100. public static TimeZoneInfo Utc {
  101. get {
  102. if (utc == null)
  103. utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
  104. return utc;
  105. }
  106. }
  107. #if LIBC
  108. static string timeZoneDirectory = null;
  109. static string TimeZoneDirectory {
  110. get {
  111. if (timeZoneDirectory == null)
  112. timeZoneDirectory = "/usr/share/zoneinfo";
  113. return timeZoneDirectory;
  114. }
  115. set {
  116. ClearCachedData ();
  117. timeZoneDirectory = value;
  118. }
  119. }
  120. #endif
  121. private AdjustmentRule [] adjustmentRules;
  122. #if !NET_2_1
  123. static RegistryKey timeZoneKey = null;
  124. static bool timeZoneKeySet = false;
  125. static RegistryKey TimeZoneKey {
  126. get {
  127. if (!timeZoneKeySet) {
  128. int p = (int) Environment.OSVersion.Platform;
  129. /* Only use the registry on non-Unix platforms. */
  130. if ((p != 4) && (p != 6) && (p != 128))
  131. timeZoneKey = Registry.LocalMachine.OpenSubKey (
  132. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
  133. false);
  134. timeZoneKeySet = true;
  135. }
  136. return timeZoneKey;
  137. }
  138. }
  139. #endif
  140. public static void ClearCachedData ()
  141. {
  142. local = null;
  143. utc = null;
  144. systemTimeZones = null;
  145. }
  146. public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
  147. {
  148. return ConvertTime (dateTime, TimeZoneInfo.Local, destinationTimeZone);
  149. }
  150. public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
  151. {
  152. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
  153. throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
  154. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
  155. throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
  156. if (sourceTimeZone.IsInvalidTime (dateTime))
  157. throw new ArgumentException ("dateTime parameter is an invalid time");
  158. if (sourceTimeZone == null)
  159. throw new ArgumentNullException ("sourceTimeZone");
  160. if (destinationTimeZone == null)
  161. throw new ArgumentNullException ("destinationTimeZone");
  162. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
  163. return dateTime;
  164. DateTime utc = ConvertTimeToUtc (dateTime);
  165. if (destinationTimeZone == TimeZoneInfo.Utc)
  166. return utc;
  167. return ConvertTimeFromUtc (utc, destinationTimeZone);
  168. }
  169. public static DateTimeOffset ConvertTime (DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
  170. {
  171. throw new NotImplementedException ();
  172. }
  173. public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
  174. {
  175. return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
  176. }
  177. public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
  178. {
  179. return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
  180. }
  181. public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
  182. {
  183. return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
  184. }
  185. private DateTime ConvertTimeFromUtc (DateTime dateTime)
  186. {
  187. if (dateTime.Kind == DateTimeKind.Local)
  188. throw new ArgumentException ("Kind property of dateTime is Local");
  189. if (this == TimeZoneInfo.Utc)
  190. return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
  191. //FIXME: do not rely on DateTime implementation !
  192. if (this == TimeZoneInfo.Local)
  193. return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
  194. AdjustmentRule rule = GetApplicableRule (dateTime);
  195. if (IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
  196. return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
  197. else
  198. return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
  199. }
  200. public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
  201. {
  202. if (destinationTimeZone == null)
  203. throw new ArgumentNullException ("destinationTimeZone");
  204. return destinationTimeZone.ConvertTimeFromUtc (dateTime);
  205. }
  206. public static DateTime ConvertTimeToUtc (DateTime dateTime)
  207. {
  208. if (dateTime.Kind == DateTimeKind.Utc)
  209. return dateTime;
  210. //FIXME: do not rely on DateTime implementation !
  211. return DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc);
  212. }
  213. public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
  214. {
  215. if (sourceTimeZone == null)
  216. throw new ArgumentNullException ("sourceTimeZone");
  217. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
  218. throw new ArgumentException ("Kind propery of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
  219. if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
  220. throw new ArgumentException ("Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
  221. if (sourceTimeZone.IsInvalidTime (dateTime))
  222. throw new ArgumentException ("dateTime parameter is an invalid time");
  223. if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone == TimeZoneInfo.Utc)
  224. return dateTime;
  225. if (dateTime.Kind == DateTimeKind.Utc)
  226. return dateTime;
  227. if (dateTime.Kind == DateTimeKind.Local)
  228. return ConvertTimeToUtc (dateTime);
  229. if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
  230. return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
  231. else {
  232. AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
  233. return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
  234. }
  235. }
  236. public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
  237. {
  238. return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
  239. }
  240. public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
  241. {
  242. return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
  243. }
  244. public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  245. {
  246. return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
  247. }
  248. public bool Equals (TimeZoneInfo other)
  249. {
  250. if (other == null)
  251. return false;
  252. return other.Id == this.Id && HasSameRules (other);
  253. }
  254. public static TimeZoneInfo FindSystemTimeZoneById (string id)
  255. {
  256. //FIXME: this method should check for cached values in systemTimeZones
  257. if (id == null)
  258. throw new ArgumentNullException ("id");
  259. #if !NET_2_1
  260. if (TimeZoneKey != null)
  261. {
  262. RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
  263. if (key == null)
  264. throw new TimeZoneNotFoundException ();
  265. return FromRegistryKey(id, key);
  266. }
  267. #endif
  268. #if LIBC
  269. string filepath = Path.Combine (TimeZoneDirectory, id);
  270. return FindSystemTimeZoneByFileName (id, filepath);
  271. #else
  272. throw new NotImplementedException ();
  273. #endif
  274. }
  275. #if LIBC
  276. const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
  277. private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
  278. {
  279. if (!File.Exists (filepath))
  280. throw new TimeZoneNotFoundException ();
  281. byte [] buffer = new byte [BUFFER_SIZE];
  282. int length;
  283. using (FileStream stream = File.OpenRead (filepath)) {
  284. length = stream.Read (buffer, 0, BUFFER_SIZE);
  285. }
  286. if (!ValidTZFile (buffer, length))
  287. throw new InvalidTimeZoneException ("TZ file too big for the buffer");
  288. try {
  289. return ParseTZBuffer (id, buffer, length);
  290. } catch (Exception e) {
  291. throw new InvalidTimeZoneException (e.Message);
  292. }
  293. }
  294. #endif
  295. #if !NET_2_1
  296. private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
  297. {
  298. byte [] reg_tzi = (byte []) key.GetValue ("TZI");
  299. if (reg_tzi == null)
  300. throw new InvalidTimeZoneException ();
  301. int bias = BitConverter.ToInt32 (reg_tzi, 0);
  302. TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
  303. string display_name = (string) key.GetValue ("Display");
  304. string standard_name = (string) key.GetValue ("Std");
  305. string daylight_name = (string) key.GetValue ("Dlt");
  306. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  307. RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
  308. if (dst_key != null) {
  309. int first_year = (int) dst_key.GetValue ("FirstEntry");
  310. int last_year = (int) dst_key.GetValue ("LastEntry");
  311. int year;
  312. for (year=first_year; year<=last_year; year++) {
  313. byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
  314. if (dst_tzi != null) {
  315. int start_year = year == first_year ? 1 : year;
  316. int end_year = year == last_year ? 9999 : year;
  317. ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
  318. }
  319. }
  320. }
  321. else
  322. ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
  323. return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
  324. }
  325. private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
  326. {
  327. //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
  328. int daylight_bias = BitConverter.ToInt32 (buffer, 8);
  329. int standard_year = BitConverter.ToInt16 (buffer, 12);
  330. int standard_month = BitConverter.ToInt16 (buffer, 14);
  331. int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
  332. int standard_day = BitConverter.ToInt16 (buffer, 18);
  333. int standard_hour = BitConverter.ToInt16 (buffer, 20);
  334. int standard_minute = BitConverter.ToInt16 (buffer, 22);
  335. int standard_second = BitConverter.ToInt16 (buffer, 24);
  336. int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
  337. int daylight_year = BitConverter.ToInt16 (buffer, 28);
  338. int daylight_month = BitConverter.ToInt16 (buffer, 30);
  339. int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
  340. int daylight_day = BitConverter.ToInt16 (buffer, 34);
  341. int daylight_hour = BitConverter.ToInt16 (buffer, 36);
  342. int daylight_minute = BitConverter.ToInt16 (buffer, 38);
  343. int daylight_second = BitConverter.ToInt16 (buffer, 40);
  344. int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
  345. if (standard_month == 0 || daylight_month == 0)
  346. return;
  347. DateTime start_date;
  348. DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
  349. TransitionTime start_transition_time;
  350. if (daylight_year == 0) {
  351. start_date = new DateTime (start_year, 1, 1);
  352. start_transition_time = TransitionTime.CreateFloatingDateRule (
  353. start_timeofday, daylight_month, daylight_day,
  354. (DayOfWeek) daylight_dayofweek);
  355. }
  356. else {
  357. start_date = new DateTime (daylight_year, daylight_month, daylight_day,
  358. daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
  359. start_transition_time = TransitionTime.CreateFixedDateRule (
  360. start_timeofday, daylight_month, daylight_day);
  361. }
  362. DateTime end_date;
  363. DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
  364. TransitionTime end_transition_time;
  365. if (standard_year == 0) {
  366. end_date = new DateTime (end_year, 12, 31);
  367. end_transition_time = TransitionTime.CreateFloatingDateRule (
  368. end_timeofday, standard_month, standard_day,
  369. (DayOfWeek) standard_dayofweek);
  370. }
  371. else {
  372. end_date = new DateTime (standard_year, standard_month, standard_day,
  373. standard_hour, standard_minute, standard_second, standard_millisecond);
  374. end_transition_time = TransitionTime.CreateFixedDateRule (
  375. end_timeofday, standard_month, standard_day);
  376. }
  377. TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
  378. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
  379. start_date, end_date, daylight_delta,
  380. start_transition_time, end_transition_time));
  381. }
  382. #endif
  383. public static TimeZoneInfo FromSerializedString (string source)
  384. {
  385. throw new NotImplementedException ();
  386. }
  387. public AdjustmentRule [] GetAdjustmentRules ()
  388. {
  389. if (disableDaylightSavingTime)
  390. return new AdjustmentRule [0];
  391. else
  392. return (AdjustmentRule []) adjustmentRules.Clone ();
  393. }
  394. public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
  395. {
  396. if (!IsAmbiguousTime (dateTime))
  397. throw new ArgumentException ("dateTime is not an ambiguous time");
  398. AdjustmentRule rule = GetApplicableRule (dateTime);
  399. return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
  400. }
  401. public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
  402. {
  403. if (!IsAmbiguousTime (dateTimeOffset))
  404. throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
  405. throw new NotImplementedException ();
  406. }
  407. public override int GetHashCode ()
  408. {
  409. int hash_code = Id.GetHashCode ();
  410. foreach (AdjustmentRule rule in GetAdjustmentRules ())
  411. hash_code ^= rule.GetHashCode ();
  412. return hash_code;
  413. }
  414. #if NET_4_0
  415. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  416. #else
  417. public void GetObjectData (SerializationInfo info, StreamingContext context)
  418. #endif
  419. {
  420. throw new NotImplementedException ();
  421. }
  422. //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
  423. private static List<TimeZoneInfo> systemTimeZones = null;
  424. public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
  425. {
  426. if (systemTimeZones == null) {
  427. systemTimeZones = new List<TimeZoneInfo> ();
  428. #if !NET_2_1
  429. if (TimeZoneKey != null) {
  430. foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
  431. try {
  432. systemTimeZones.Add (FindSystemTimeZoneById (id));
  433. } catch {}
  434. }
  435. return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
  436. }
  437. #endif
  438. #if LIBC
  439. string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
  440. foreach (string continent in continents) {
  441. try {
  442. foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
  443. try {
  444. string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
  445. systemTimeZones.Add (FindSystemTimeZoneById (id));
  446. } catch (ArgumentNullException) {
  447. } catch (TimeZoneNotFoundException) {
  448. } catch (InvalidTimeZoneException) {
  449. } catch (Exception) {
  450. throw;
  451. }
  452. }
  453. } catch {}
  454. }
  455. #else
  456. throw new NotImplementedException ("This method is not implemented for this platform");
  457. #endif
  458. }
  459. return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
  460. }
  461. public TimeSpan GetUtcOffset (DateTime dateTime)
  462. {
  463. if (IsDaylightSavingTime (dateTime)) {
  464. AdjustmentRule rule = GetApplicableRule (dateTime);
  465. return BaseUtcOffset + rule.DaylightDelta;
  466. }
  467. return BaseUtcOffset;
  468. }
  469. public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
  470. {
  471. throw new NotImplementedException ();
  472. }
  473. public bool HasSameRules (TimeZoneInfo other)
  474. {
  475. if (other == null)
  476. throw new ArgumentNullException ("other");
  477. if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
  478. return false;
  479. if (this.adjustmentRules == null)
  480. return true;
  481. if (this.BaseUtcOffset != other.BaseUtcOffset)
  482. return false;
  483. if (this.adjustmentRules.Length != other.adjustmentRules.Length)
  484. return false;
  485. for (int i = 0; i < adjustmentRules.Length; i++) {
  486. if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
  487. return false;
  488. }
  489. return true;
  490. }
  491. public bool IsAmbiguousTime (DateTime dateTime)
  492. {
  493. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  494. throw new ArgumentException ("Kind is Local and time is Invalid");
  495. if (this == TimeZoneInfo.Utc)
  496. return false;
  497. if (dateTime.Kind == DateTimeKind.Utc)
  498. dateTime = ConvertTimeFromUtc (dateTime);
  499. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  500. dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
  501. AdjustmentRule rule = GetApplicableRule (dateTime);
  502. DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
  503. if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
  504. return true;
  505. return false;
  506. }
  507. public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
  508. {
  509. throw new NotImplementedException ();
  510. }
  511. public bool IsDaylightSavingTime (DateTime dateTime)
  512. {
  513. if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
  514. throw new ArgumentException ("dateTime is invalid and Kind is Local");
  515. if (this == TimeZoneInfo.Utc)
  516. return false;
  517. if (!SupportsDaylightSavingTime)
  518. return false;
  519. //FIXME: do not rely on DateTime implementation !
  520. if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
  521. return dateTime.IsDaylightSavingTime ();
  522. //FIXME: do not rely on DateTime implementation !
  523. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
  524. return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
  525. AdjustmentRule rule = GetApplicableRule (dateTime.Date);
  526. if (rule == null)
  527. return false;
  528. DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  529. DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
  530. if (dateTime.Kind == DateTimeKind.Utc) {
  531. DST_start -= BaseUtcOffset;
  532. DST_end -= (BaseUtcOffset + rule.DaylightDelta);
  533. }
  534. return (dateTime >= DST_start && dateTime < DST_end);
  535. }
  536. public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
  537. {
  538. throw new NotImplementedException ();
  539. }
  540. public bool IsInvalidTime (DateTime dateTime)
  541. {
  542. if (dateTime.Kind == DateTimeKind.Utc)
  543. return false;
  544. if (dateTime.Kind == DateTimeKind.Local && this != Local)
  545. return false;
  546. AdjustmentRule rule = GetApplicableRule (dateTime);
  547. DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
  548. if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
  549. return true;
  550. return false;
  551. }
  552. #if NET_4_0
  553. void IDeserializationCallback.OnDeserialization (object sender)
  554. #else
  555. public void OnDeserialization (object sender)
  556. #endif
  557. {
  558. throw new NotImplementedException ();
  559. }
  560. public string ToSerializedString ()
  561. {
  562. throw new NotImplementedException ();
  563. }
  564. public override string ToString ()
  565. {
  566. return DisplayName;
  567. }
  568. private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
  569. {
  570. if (id == null)
  571. throw new ArgumentNullException ("id");
  572. if (id == String.Empty)
  573. throw new ArgumentException ("id parameter is an empty string");
  574. if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  575. throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
  576. if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
  577. throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
  578. #if STRICT
  579. if (id.Length > 32)
  580. throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
  581. #endif
  582. if (adjustmentRules != null && adjustmentRules.Length != 0) {
  583. AdjustmentRule prev = null;
  584. foreach (AdjustmentRule current in adjustmentRules) {
  585. if (current == null)
  586. throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
  587. if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
  588. (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
  589. 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;");
  590. if (prev != null && prev.DateStart > current.DateStart)
  591. throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
  592. if (prev != null && prev.DateEnd > current.DateStart)
  593. throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
  594. if (prev != null && prev.DateEnd == current.DateStart)
  595. throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
  596. prev = current;
  597. }
  598. }
  599. this.id = id;
  600. this.baseUtcOffset = baseUtcOffset;
  601. this.displayName = displayName ?? id;
  602. this.standardDisplayName = standardDisplayName ?? id;
  603. this.daylightDisplayName = daylightDisplayName;
  604. this.disableDaylightSavingTime = disableDaylightSavingTime;
  605. this.adjustmentRules = adjustmentRules;
  606. }
  607. private AdjustmentRule GetApplicableRule (DateTime dateTime)
  608. {
  609. //Transitions are always in standard time
  610. DateTime date = dateTime;
  611. if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
  612. date = date.ToUniversalTime () + BaseUtcOffset;
  613. if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
  614. date = date + BaseUtcOffset;
  615. if (adjustmentRules != null) {
  616. foreach (AdjustmentRule rule in adjustmentRules) {
  617. if (rule.DateStart > date.Date)
  618. return null;
  619. if (rule.DateEnd < date.Date)
  620. continue;
  621. return rule;
  622. }
  623. }
  624. return null;
  625. }
  626. private static DateTime TransitionPoint (TransitionTime transition, int year)
  627. {
  628. if (transition.IsFixedDateRule)
  629. return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
  630. DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
  631. int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
  632. if (day > DateTime.DaysInMonth (year, transition.Month))
  633. day -= 7;
  634. return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
  635. }
  636. static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
  637. {
  638. AdjustmentRule prev = null;
  639. foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
  640. if (prev != null && prev.DateEnd > current.DateStart) {
  641. adjustmentRules.Remove (current);
  642. }
  643. prev = current;
  644. }
  645. return adjustmentRules;
  646. }
  647. #if LIBC
  648. private static bool ValidTZFile (byte [] buffer, int length)
  649. {
  650. StringBuilder magic = new StringBuilder ();
  651. for (int i = 0; i < 4; i++)
  652. magic.Append ((char)buffer [i]);
  653. if (magic.ToString () != "TZif")
  654. return false;
  655. if (length >= BUFFER_SIZE)
  656. return false;
  657. return true;
  658. }
  659. struct TimeType
  660. {
  661. public readonly int Offset;
  662. public readonly bool IsDst;
  663. public string Name;
  664. public TimeType (int offset, bool is_dst, string abbrev)
  665. {
  666. this.Offset = offset;
  667. this.IsDst = is_dst;
  668. this.Name = abbrev;
  669. }
  670. public override string ToString ()
  671. {
  672. return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
  673. }
  674. }
  675. static int SwapInt32 (int i)
  676. {
  677. return (((i >> 24) & 0xff)
  678. | ((i >> 8) & 0xff00)
  679. | ((i << 8) & 0xff0000)
  680. | ((i << 24)));
  681. }
  682. static int ReadBigEndianInt32 (byte [] buffer, int start)
  683. {
  684. int i = BitConverter.ToInt32 (buffer, start);
  685. if (!BitConverter.IsLittleEndian)
  686. return i;
  687. return SwapInt32 (i);
  688. }
  689. private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
  690. {
  691. //Reading the header. 4 bytes for magic, 16 are reserved
  692. int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
  693. int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
  694. int leapcnt = ReadBigEndianInt32 (buffer, 28);
  695. int timecnt = ReadBigEndianInt32 (buffer, 32);
  696. int typecnt = ReadBigEndianInt32 (buffer, 36);
  697. int charcnt = ReadBigEndianInt32 (buffer, 40);
  698. if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
  699. throw new InvalidTimeZoneException ();
  700. Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
  701. Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
  702. List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
  703. if (time_types.Count == 0)
  704. throw new InvalidTimeZoneException ();
  705. if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
  706. throw new InvalidTimeZoneException ();
  707. TimeSpan baseUtcOffset = new TimeSpan (0);
  708. TimeSpan dstDelta = new TimeSpan (0);
  709. string standardDisplayName = null;
  710. string daylightDisplayName = null;
  711. bool dst_observed = false;
  712. DateTime dst_start = DateTime.MinValue;
  713. List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
  714. for (int i = 0; i < transitions.Count; i++) {
  715. var pair = transitions [i];
  716. DateTime ttime = pair.Key;
  717. TimeType ttype = pair.Value;
  718. if (!ttype.IsDst) {
  719. if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
  720. standardDisplayName = ttype.Name;
  721. daylightDisplayName = null;
  722. baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
  723. adjustmentRules = new List<AdjustmentRule> ();
  724. dst_observed = false;
  725. }
  726. if (dst_observed) {
  727. //FIXME: check additional fields for this:
  728. //most of the transitions are expressed in GMT
  729. dst_start += baseUtcOffset;
  730. DateTime dst_end = ttime + baseUtcOffset + dstDelta;
  731. //some weird timezone (America/Phoenix) have end dates on Jan 1st
  732. if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
  733. dst_end -= new TimeSpan (24, 0, 0);
  734. DateTime dateStart, dateEnd;
  735. if (dst_start.Month < 7)
  736. dateStart = new DateTime (dst_start.Year, 1, 1);
  737. else
  738. dateStart = new DateTime (dst_start.Year, 7, 1);
  739. if (dst_end.Month >= 7)
  740. dateEnd = new DateTime (dst_end.Year, 12, 31);
  741. else
  742. dateEnd = new DateTime (dst_end.Year, 6, 30);
  743. TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
  744. TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
  745. if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
  746. adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
  747. }
  748. dst_observed = false;
  749. } else {
  750. if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
  751. daylightDisplayName = ttype.Name;
  752. dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
  753. }
  754. dst_start = ttime;
  755. dst_observed = true;
  756. }
  757. }
  758. if (adjustmentRules.Count == 0) {
  759. TimeType t = (TimeType)time_types [0];
  760. if (standardDisplayName == null) {
  761. standardDisplayName = t.Name;
  762. baseUtcOffset = new TimeSpan (0, 0, t.Offset);
  763. }
  764. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
  765. } else {
  766. return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
  767. }
  768. }
  769. static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
  770. {
  771. var abbrevs = new Dictionary<int, string> ();
  772. int abbrev_index = 0;
  773. var sb = new StringBuilder ();
  774. for (int i = 0; i < count; i++) {
  775. char c = (char) buffer [index + i];
  776. if (c != '\0')
  777. sb.Append (c);
  778. else {
  779. abbrevs.Add (abbrev_index, sb.ToString ());
  780. //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
  781. for (int j = 1; j < sb.Length; j++)
  782. abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
  783. abbrev_index = i + 1;
  784. sb = new StringBuilder ();
  785. }
  786. }
  787. return abbrevs;
  788. }
  789. static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
  790. {
  791. var types = new Dictionary<int, TimeType> (count);
  792. for (int i = 0; i < count; i++) {
  793. int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
  794. byte is_dst = buffer [index + 6 * i + 4];
  795. byte abbrev = buffer [index + 6 * i + 5];
  796. types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
  797. }
  798. return types;
  799. }
  800. static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
  801. {
  802. var list = new List<KeyValuePair<DateTime, TimeType>> (count);
  803. for (int i = 0; i < count; i++) {
  804. int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
  805. DateTime ttime = DateTimeFromUnixTime (unixtime);
  806. byte ttype = buffer [index + 4 * count + i];
  807. list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
  808. }
  809. return list;
  810. }
  811. static DateTime DateTimeFromUnixTime (long unix_time)
  812. {
  813. DateTime date_time = new DateTime (1970, 1, 1);
  814. return date_time.AddSeconds (unix_time);
  815. }
  816. #endif
  817. }
  818. }
  819. #endif