5 * Stephane Delcroix <stephane@delcroix.org>
7 * Copyright 2011 Xamarin Inc.
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:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
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.
30 using System.Runtime.CompilerServices;
32 #if !INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)
34 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
36 #elif (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT || MOBILE)) || (!INSIDE_CORLIB && (NET_3_5 && !NET_4_0 && !MOBILE))
38 using System.Collections.Generic;
39 using System.Collections.ObjectModel;
40 using System.Runtime.Serialization;
48 using Microsoft.Win32;
53 [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
54 #elif MOONLIGHT || MOBILE
55 [TypeForwardedFrom (Consts.AssemblySystem_Core)]
57 [SerializableAttribute]
58 public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
60 TimeSpan baseUtcOffset;
61 public TimeSpan BaseUtcOffset {
62 get { return baseUtcOffset; }
65 string daylightDisplayName;
66 public string DaylightName {
68 return supportsDaylightSavingTime
75 public string DisplayName {
76 get { return displayName; }
84 static TimeZoneInfo local;
85 public static TimeZoneInfo Local {
89 local = ZoneInfoDB.Default;
91 using (Stream stream = GetMonoTouchDefault ()) {
92 local = BuildFromStream ("Local", stream);
96 local = FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
99 local = FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
101 throw new TimeZoneNotFoundException ();
105 if (IsWindows && LocalZoneKey != null) {
106 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
107 name = TrimSpecial (name);
109 local = TimeZoneInfo.FindSystemTimeZoneById (name);
113 throw new TimeZoneNotFoundException ();
120 string standardDisplayName;
121 public string StandardName {
122 get { return standardDisplayName; }
125 bool supportsDaylightSavingTime;
126 public bool SupportsDaylightSavingTime {
127 get { return supportsDaylightSavingTime; }
130 static TimeZoneInfo utc;
131 public static TimeZoneInfo Utc {
134 utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
139 static string timeZoneDirectory;
140 static string TimeZoneDirectory {
142 if (timeZoneDirectory == null)
143 timeZoneDirectory = "/usr/share/zoneinfo";
144 return timeZoneDirectory;
148 timeZoneDirectory = value;
152 private AdjustmentRule [] adjustmentRules;
156 /// Determine whether windows of not (taken Stephane Delcroix's code)
158 private static bool IsWindows
161 int platform = (int) Environment.OSVersion.Platform;
162 return ((platform != 4) && (platform != 6) && (platform != 128));
167 /// Needed to trim misc garbage in MS registry keys
169 private static string TrimSpecial (string str)
172 while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
173 var Iend = str.Length - 1;
174 while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
176 return str.Substring (Istart, Iend-Istart+1);
179 static RegistryKey timeZoneKey;
180 static RegistryKey TimeZoneKey {
182 if (timeZoneKey != null)
187 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
188 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
193 static RegistryKey localZoneKey;
194 static RegistryKey LocalZoneKey {
196 if (localZoneKey != null)
202 return localZoneKey = Registry.LocalMachine.OpenSubKey (
203 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
208 public static void ClearCachedData ()
212 systemTimeZones = null;
215 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
217 return ConvertTime (dateTime, TimeZoneInfo.Local, destinationTimeZone);
220 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
222 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
223 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
225 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
226 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
228 if (sourceTimeZone.IsInvalidTime (dateTime))
229 throw new ArgumentException ("dateTime parameter is an invalid time");
231 if (sourceTimeZone == null)
232 throw new ArgumentNullException ("sourceTimeZone");
234 if (destinationTimeZone == null)
235 throw new ArgumentNullException ("destinationTimeZone");
237 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
240 DateTime utc = ConvertTimeToUtc (dateTime);
242 if (destinationTimeZone == TimeZoneInfo.Utc)
245 return ConvertTimeFromUtc (utc, destinationTimeZone);
249 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
251 if (destinationTimeZone == null)
252 throw new ArgumentNullException("destinationTimeZone");
254 var utcDateTime = dateTimeOffset.UtcDateTime;
255 AdjustmentRule rule = GetApplicableRule (utcDateTime);
257 if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
258 var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
259 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
262 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
266 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
268 return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
271 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
273 return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
276 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
278 return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
281 private DateTime ConvertTimeFromUtc (DateTime dateTime)
283 if (dateTime.Kind == DateTimeKind.Local)
284 throw new ArgumentException ("Kind property of dateTime is Local");
286 if (this == TimeZoneInfo.Utc)
287 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
289 //FIXME: do not rely on DateTime implementation !
290 if (this == TimeZoneInfo.Local)
291 return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
293 AdjustmentRule rule = GetApplicableRule (dateTime);
295 if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
296 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
298 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
301 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
303 if (destinationTimeZone == null)
304 throw new ArgumentNullException ("destinationTimeZone");
306 return destinationTimeZone.ConvertTimeFromUtc (dateTime);
309 public static DateTime ConvertTimeToUtc (DateTime dateTime)
311 if (dateTime.Kind == DateTimeKind.Utc)
314 //FIXME: do not rely on DateTime implementation !
315 return DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc);
318 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
320 if (sourceTimeZone == null)
321 throw new ArgumentNullException ("sourceTimeZone");
323 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
324 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
326 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
327 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
329 if (sourceTimeZone.IsInvalidTime (dateTime))
330 throw new ArgumentException ("dateTime parameter is an invalid time");
332 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone == TimeZoneInfo.Utc)
335 if (dateTime.Kind == DateTimeKind.Utc)
338 if (dateTime.Kind == DateTimeKind.Local)
339 return ConvertTimeToUtc (dateTime);
341 if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
342 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
344 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
346 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
348 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
352 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
354 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
357 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
359 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
362 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
364 return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
368 public override bool Equals (object obj)
370 return Equals (obj as TimeZoneInfo);
374 public bool Equals (TimeZoneInfo other)
379 return other.Id == this.Id && HasSameRules (other);
382 public static TimeZoneInfo FindSystemTimeZoneById (string id)
384 //FIXME: this method should check for cached values in systemTimeZones
386 throw new ArgumentNullException ("id");
388 if (TimeZoneKey != null)
390 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
392 throw new TimeZoneNotFoundException ();
393 return FromRegistryKey(id, key);
397 var timeZoneInfo = ZoneInfoDB.GetTimeZone (id);
398 if (timeZoneInfo == null)
399 throw new TimeZoneNotFoundException ();
402 // Local requires special logic that already exists in the Local property (bug #326)
406 using (Stream stream = GetMonoTouchData (id)) {
407 return BuildFromStream (id, stream);
410 string filepath = Path.Combine (TimeZoneDirectory, id);
411 return FindSystemTimeZoneByFileName (id, filepath);
413 throw new NotImplementedException ();
419 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
421 if (!File.Exists (filepath))
422 throw new TimeZoneNotFoundException ();
424 using (FileStream stream = File.OpenRead (filepath)) {
425 return BuildFromStream (id, stream);
429 #if LIBC || MONOTOUCH
430 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
432 private static TimeZoneInfo BuildFromStream (string id, Stream stream)
434 byte [] buffer = new byte [BUFFER_SIZE];
435 int length = stream.Read (buffer, 0, BUFFER_SIZE);
437 if (!ValidTZFile (buffer, length))
438 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
441 return ParseTZBuffer (id, buffer, length);
442 } catch (Exception e) {
443 throw new InvalidTimeZoneException (e.Message);
449 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
451 byte [] reg_tzi = (byte []) key.GetValue ("TZI");
454 throw new InvalidTimeZoneException ();
456 int bias = BitConverter.ToInt32 (reg_tzi, 0);
457 TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
459 string display_name = (string) key.GetValue ("Display");
460 string standard_name = (string) key.GetValue ("Std");
461 string daylight_name = (string) key.GetValue ("Dlt");
463 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
465 RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
466 if (dst_key != null) {
467 int first_year = (int) dst_key.GetValue ("FirstEntry");
468 int last_year = (int) dst_key.GetValue ("LastEntry");
471 for (year=first_year; year<=last_year; year++) {
472 byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
473 if (dst_tzi != null) {
474 int start_year = year == first_year ? 1 : year;
475 int end_year = year == last_year ? 9999 : year;
476 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
481 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
483 return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
486 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
488 //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
489 int daylight_bias = BitConverter.ToInt32 (buffer, 8);
491 int standard_year = BitConverter.ToInt16 (buffer, 12);
492 int standard_month = BitConverter.ToInt16 (buffer, 14);
493 int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
494 int standard_day = BitConverter.ToInt16 (buffer, 18);
495 int standard_hour = BitConverter.ToInt16 (buffer, 20);
496 int standard_minute = BitConverter.ToInt16 (buffer, 22);
497 int standard_second = BitConverter.ToInt16 (buffer, 24);
498 int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
500 int daylight_year = BitConverter.ToInt16 (buffer, 28);
501 int daylight_month = BitConverter.ToInt16 (buffer, 30);
502 int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
503 int daylight_day = BitConverter.ToInt16 (buffer, 34);
504 int daylight_hour = BitConverter.ToInt16 (buffer, 36);
505 int daylight_minute = BitConverter.ToInt16 (buffer, 38);
506 int daylight_second = BitConverter.ToInt16 (buffer, 40);
507 int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
509 if (standard_month == 0 || daylight_month == 0)
513 DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
514 TransitionTime start_transition_time;
516 if (daylight_year == 0) {
517 start_date = new DateTime (start_year, 1, 1);
518 start_transition_time = TransitionTime.CreateFloatingDateRule (
519 start_timeofday, daylight_month, daylight_day,
520 (DayOfWeek) daylight_dayofweek);
523 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
524 daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
525 start_transition_time = TransitionTime.CreateFixedDateRule (
526 start_timeofday, daylight_month, daylight_day);
530 DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
531 TransitionTime end_transition_time;
533 if (standard_year == 0) {
534 end_date = new DateTime (end_year, 12, 31);
535 end_transition_time = TransitionTime.CreateFloatingDateRule (
536 end_timeofday, standard_month, standard_day,
537 (DayOfWeek) standard_dayofweek);
540 end_date = new DateTime (standard_year, standard_month, standard_day,
541 standard_hour, standard_minute, standard_second, standard_millisecond);
542 end_transition_time = TransitionTime.CreateFixedDateRule (
543 end_timeofday, standard_month, standard_day);
546 TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
548 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
549 start_date, end_date, daylight_delta,
550 start_transition_time, end_transition_time));
554 public static TimeZoneInfo FromSerializedString (string source)
556 throw new NotImplementedException ();
559 public AdjustmentRule [] GetAdjustmentRules ()
561 if (!supportsDaylightSavingTime)
562 return new AdjustmentRule [0];
564 return (AdjustmentRule []) adjustmentRules.Clone ();
567 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
569 if (!IsAmbiguousTime (dateTime))
570 throw new ArgumentException ("dateTime is not an ambiguous time");
572 AdjustmentRule rule = GetApplicableRule (dateTime);
574 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
576 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
579 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
581 if (!IsAmbiguousTime (dateTimeOffset))
582 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
584 throw new NotImplementedException ();
587 public override int GetHashCode ()
589 int hash_code = Id.GetHashCode ();
590 foreach (AdjustmentRule rule in GetAdjustmentRules ())
591 hash_code ^= rule.GetHashCode ();
596 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
598 public void GetObjectData (SerializationInfo info, StreamingContext context)
601 throw new NotImplementedException ();
604 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
605 private static List<TimeZoneInfo> systemTimeZones;
606 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
608 if (systemTimeZones == null) {
609 systemTimeZones = new List<TimeZoneInfo> ();
611 if (TimeZoneKey != null) {
612 foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
614 systemTimeZones.Add (FindSystemTimeZoneById (id));
618 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
622 foreach (string id in ZoneInfoDB.GetAvailableIds ()) {
623 var tz = ZoneInfoDB.GetTimeZone (id);
625 systemTimeZones.Add (tz);
628 if (systemTimeZones.Count == 0) {
629 foreach (string name in GetMonoTouchNames ()) {
630 using (Stream stream = GetMonoTouchData (name)) {
631 systemTimeZones.Add (BuildFromStream (name, stream));
636 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
637 foreach (string continent in continents) {
639 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
641 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
642 systemTimeZones.Add (FindSystemTimeZoneById (id));
643 } catch (ArgumentNullException) {
644 } catch (TimeZoneNotFoundException) {
645 } catch (InvalidTimeZoneException) {
646 } catch (Exception) {
653 throw new NotImplementedException ("This method is not implemented for this platform");
656 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
659 public TimeSpan GetUtcOffset (DateTime dateTime)
661 if (IsDaylightSavingTime (dateTime)) {
662 AdjustmentRule rule = GetApplicableRule (dateTime);
664 return BaseUtcOffset + rule.DaylightDelta;
667 return BaseUtcOffset;
670 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
672 throw new NotImplementedException ();
675 public bool HasSameRules (TimeZoneInfo other)
678 throw new ArgumentNullException ("other");
680 if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
683 if (this.adjustmentRules == null)
686 if (this.BaseUtcOffset != other.BaseUtcOffset)
689 if (this.adjustmentRules.Length != other.adjustmentRules.Length)
692 for (int i = 0; i < adjustmentRules.Length; i++) {
693 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
700 public bool IsAmbiguousTime (DateTime dateTime)
702 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
703 throw new ArgumentException ("Kind is Local and time is Invalid");
705 if (this == TimeZoneInfo.Utc)
708 if (dateTime.Kind == DateTimeKind.Utc)
709 dateTime = ConvertTimeFromUtc (dateTime);
711 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
712 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
714 AdjustmentRule rule = GetApplicableRule (dateTime);
716 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
717 if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
724 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
726 throw new NotImplementedException ();
729 public bool IsDaylightSavingTime (DateTime dateTime)
731 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
732 throw new ArgumentException ("dateTime is invalid and Kind is Local");
734 if (this == TimeZoneInfo.Utc)
737 if (!SupportsDaylightSavingTime)
739 //FIXME: do not rely on DateTime implementation !
740 if ((dateTime.Kind == DateTimeKind.Local || dateTime.Kind == DateTimeKind.Unspecified) && this == TimeZoneInfo.Local)
741 return dateTime.IsDaylightSavingTime ();
743 //FIXME: do not rely on DateTime implementation !
744 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Utc)
745 return IsDaylightSavingTime (DateTime.SpecifyKind (dateTime.ToUniversalTime (), DateTimeKind.Utc));
747 AdjustmentRule rule = GetApplicableRule (dateTime.Date);
751 DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
752 DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
753 if (dateTime.Kind == DateTimeKind.Utc) {
754 DST_start -= BaseUtcOffset;
755 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
758 return (dateTime >= DST_start && dateTime < DST_end);
761 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
763 throw new NotImplementedException ();
766 public bool IsInvalidTime (DateTime dateTime)
768 if (dateTime.Kind == DateTimeKind.Utc)
770 if (dateTime.Kind == DateTimeKind.Local && this != Local)
773 AdjustmentRule rule = GetApplicableRule (dateTime);
775 DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
776 if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
784 void IDeserializationCallback.OnDeserialization (object sender)
786 public void OnDeserialization (object sender)
789 throw new NotImplementedException ();
792 public string ToSerializedString ()
794 throw new NotImplementedException ();
797 public override string ToString ()
802 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
805 throw new ArgumentNullException ("id");
807 if (id == String.Empty)
808 throw new ArgumentException ("id parameter is an empty string");
810 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
811 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
813 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
814 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
818 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
821 bool supportsDaylightSavingTime = !disableDaylightSavingTime;
823 if (adjustmentRules != null && adjustmentRules.Length != 0) {
824 AdjustmentRule prev = null;
825 foreach (AdjustmentRule current in adjustmentRules) {
827 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
829 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
830 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
831 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;");
833 if (prev != null && prev.DateStart > current.DateStart)
834 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
836 if (prev != null && prev.DateEnd > current.DateStart)
837 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
839 if (prev != null && prev.DateEnd == current.DateStart)
840 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
845 supportsDaylightSavingTime = false;
849 this.baseUtcOffset = baseUtcOffset;
850 this.displayName = displayName ?? id;
851 this.standardDisplayName = standardDisplayName ?? id;
852 this.daylightDisplayName = daylightDisplayName;
853 this.supportsDaylightSavingTime = supportsDaylightSavingTime;
854 this.adjustmentRules = adjustmentRules;
857 private AdjustmentRule GetApplicableRule (DateTime dateTime)
859 //Transitions are always in standard time
860 DateTime date = dateTime;
862 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
863 date = date.ToUniversalTime () + BaseUtcOffset;
865 if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
866 date = date + BaseUtcOffset;
868 if (adjustmentRules != null) {
869 foreach (AdjustmentRule rule in adjustmentRules) {
870 if (rule.DateStart > date.Date)
872 if (rule.DateEnd < date.Date)
880 private static DateTime TransitionPoint (TransitionTime transition, int year)
882 if (transition.IsFixedDateRule)
883 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
885 DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
886 int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
887 if (day > DateTime.DaysInMonth (year, transition.Month))
889 return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
892 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
894 AdjustmentRule prev = null;
895 foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
896 if (prev != null && prev.DateEnd > current.DateStart) {
897 adjustmentRules.Remove (current);
901 return adjustmentRules;
904 #if LIBC || MONODROID
905 private static bool ValidTZFile (byte [] buffer, int length)
907 StringBuilder magic = new StringBuilder ();
909 for (int i = 0; i < 4; i++)
910 magic.Append ((char)buffer [i]);
912 if (magic.ToString () != "TZif")
915 if (length >= BUFFER_SIZE)
921 static int SwapInt32 (int i)
923 return (((i >> 24) & 0xff)
924 | ((i >> 8) & 0xff00)
925 | ((i << 8) & 0xff0000)
929 static int ReadBigEndianInt32 (byte [] buffer, int start)
931 int i = BitConverter.ToInt32 (buffer, start);
932 if (!BitConverter.IsLittleEndian)
935 return SwapInt32 (i);
938 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
940 //Reading the header. 4 bytes for magic, 16 are reserved
941 int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
942 int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
943 int leapcnt = ReadBigEndianInt32 (buffer, 28);
944 int timecnt = ReadBigEndianInt32 (buffer, 32);
945 int typecnt = ReadBigEndianInt32 (buffer, 36);
946 int charcnt = ReadBigEndianInt32 (buffer, 40);
948 if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
949 throw new InvalidTimeZoneException ();
951 Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
952 Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
953 List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
955 if (time_types.Count == 0)
956 throw new InvalidTimeZoneException ();
958 if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
959 throw new InvalidTimeZoneException ();
961 TimeSpan baseUtcOffset = new TimeSpan (0);
962 TimeSpan dstDelta = new TimeSpan (0);
963 string standardDisplayName = null;
964 string daylightDisplayName = null;
965 bool dst_observed = false;
966 DateTime dst_start = DateTime.MinValue;
967 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
969 for (int i = 0; i < transitions.Count; i++) {
970 var pair = transitions [i];
971 DateTime ttime = pair.Key;
972 TimeType ttype = pair.Value;
974 if (standardDisplayName != ttype.Name || baseUtcOffset.TotalSeconds != ttype.Offset) {
975 standardDisplayName = ttype.Name;
976 daylightDisplayName = null;
977 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
978 adjustmentRules = new List<AdjustmentRule> ();
979 dst_observed = false;
982 //FIXME: check additional fields for this:
983 //most of the transitions are expressed in GMT
984 dst_start += baseUtcOffset;
985 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
987 //some weird timezone (America/Phoenix) have end dates on Jan 1st
988 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
989 dst_end -= new TimeSpan (24, 0, 0);
991 DateTime dateStart, dateEnd;
992 if (dst_start.Month < 7)
993 dateStart = new DateTime (dst_start.Year, 1, 1);
995 dateStart = new DateTime (dst_start.Year, 7, 1);
997 if (dst_end.Month >= 7)
998 dateEnd = new DateTime (dst_end.Year, 12, 31);
1000 dateEnd = new DateTime (dst_end.Year, 6, 30);
1003 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1004 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1005 if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1006 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1008 dst_observed = false;
1010 if (daylightDisplayName != ttype.Name || dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds) {
1011 daylightDisplayName = ttype.Name;
1012 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1015 dst_observed = true;
1019 if (adjustmentRules.Count == 0) {
1020 TimeType t = (TimeType)time_types [0];
1021 if (standardDisplayName == null) {
1022 standardDisplayName = t.Name;
1023 baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1025 return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1027 return CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1031 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1033 var abbrevs = new Dictionary<int, string> ();
1034 int abbrev_index = 0;
1035 var sb = new StringBuilder ();
1036 for (int i = 0; i < count; i++) {
1037 char c = (char) buffer [index + i];
1041 abbrevs.Add (abbrev_index, sb.ToString ());
1042 //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1043 for (int j = 1; j < sb.Length; j++)
1044 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1045 abbrev_index = i + 1;
1046 sb = new StringBuilder ();
1052 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1054 var types = new Dictionary<int, TimeType> (count);
1055 for (int i = 0; i < count; i++) {
1056 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1057 byte is_dst = buffer [index + 6 * i + 4];
1058 byte abbrev = buffer [index + 6 * i + 5];
1059 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1064 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1066 var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1067 for (int i = 0; i < count; i++) {
1068 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1069 DateTime ttime = DateTimeFromUnixTime (unixtime);
1070 byte ttype = buffer [index + 4 * count + i];
1071 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1076 static DateTime DateTimeFromUnixTime (long unix_time)
1078 DateTime date_time = new DateTime (1970, 1, 1);
1079 return date_time.AddSeconds (unix_time);
1084 public readonly int Offset;
1085 public readonly bool IsDst;
1088 public TimeType (int offset, bool is_dst, string abbrev)
1090 this.Offset = offset;
1091 this.IsDst = is_dst;
1095 public override string ToString ()
1097 return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;