TimeZoneInfo.cs 40 KB

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