TimeZoneInfo.cs 35 KB

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