6 * Stephane Delcroix <stephane@delcroix.org>
8 * Copyright 2011 Xamarin Inc.
10 * Permission is hereby granted, free of charge, to any person obtaining
11 * a copy of this software and associated documentation files (the
12 * "Software"), to deal in the Software without restriction, including
13 * without limitation the rights to use, copy, modify, merge, publish,
14 * distribute, sublicense, and/or sell copies of the Software, and to
15 * permit persons to whom the Software is furnished to do so, subject to
16 * the following conditions:
18 * The above copyright notice and this permission notice shall be
19 * included in all copies or substantial portions of the Software.
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Runtime.CompilerServices;
32 using System.Threading;
34 #if !INSIDE_CORLIB && NET_4_0
36 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
38 #elif INSIDE_CORLIB || (NET_3_5 && !NET_4_0 && !MOBILE)
40 using System.Collections.Generic;
41 using System.Collections.ObjectModel;
42 using System.Runtime.Serialization;
50 using Microsoft.Win32;
55 [TypeForwardedFrom (Consts.AssemblySystem_Core)]
57 [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
59 [SerializableAttribute]
60 #if NET_4_0 || !INSIDE_CORLIB
63 sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
65 TimeSpan baseUtcOffset;
66 public TimeSpan BaseUtcOffset {
67 get { return baseUtcOffset; }
70 string daylightDisplayName;
71 public string DaylightName {
73 return supportsDaylightSavingTime
80 public string DisplayName {
81 get { return displayName; }
89 static TimeZoneInfo local;
90 public static TimeZoneInfo Local {
96 throw new TimeZoneNotFoundException ();
98 if (Interlocked.CompareExchange (ref local, l, null) != null)
107 TimeZone transitions are stored when there is a change on the base offset.
109 private List<KeyValuePair<DateTime, TimeType>> transitions;
111 static TimeZoneInfo CreateLocal ()
114 return AndroidTimeZones.Local;
116 using (Stream stream = GetMonoTouchData (null)) {
117 return BuildFromStream ("Local", stream);
120 var tz = Environment.GetEnvironmentVariable ("TZ");
122 if (tz == String.Empty)
125 return FindSystemTimeZoneByFileName (tz, Path.Combine (TimeZoneDirectory, tz));
132 return FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
135 return FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
141 if (IsWindows && LocalZoneKey != null) {
142 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
143 name = TrimSpecial (name);
145 return TimeZoneInfo.FindSystemTimeZoneById (name);
152 string standardDisplayName;
153 public string StandardName {
154 get { return standardDisplayName; }
157 bool supportsDaylightSavingTime;
158 public bool SupportsDaylightSavingTime {
159 get { return supportsDaylightSavingTime; }
162 static TimeZoneInfo utc;
163 public static TimeZoneInfo Utc {
166 utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
171 static string timeZoneDirectory;
172 static string TimeZoneDirectory {
174 if (timeZoneDirectory == null)
175 timeZoneDirectory = "/usr/share/zoneinfo";
176 return timeZoneDirectory;
180 timeZoneDirectory = value;
184 private AdjustmentRule [] adjustmentRules;
188 /// Determine whether windows of not (taken Stephane Delcroix's code)
190 private static bool IsWindows
193 int platform = (int) Environment.OSVersion.Platform;
194 return ((platform != 4) && (platform != 6) && (platform != 128));
199 /// Needed to trim misc garbage in MS registry keys
201 private static string TrimSpecial (string str)
204 while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
205 var Iend = str.Length - 1;
206 while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
208 return str.Substring (Istart, Iend-Istart+1);
211 static RegistryKey timeZoneKey;
212 static RegistryKey TimeZoneKey {
214 if (timeZoneKey != null)
219 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
220 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
225 static RegistryKey localZoneKey;
226 static RegistryKey LocalZoneKey {
228 if (localZoneKey != null)
234 return localZoneKey = Registry.LocalMachine.OpenSubKey (
235 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
240 public static void ClearCachedData ()
244 systemTimeZones = null;
247 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
249 return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
252 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
254 if (sourceTimeZone == null)
255 throw new ArgumentNullException ("sourceTimeZone");
257 if (destinationTimeZone == null)
258 throw new ArgumentNullException ("destinationTimeZone");
260 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
261 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
263 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
264 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
266 if (sourceTimeZone.IsInvalidTime (dateTime))
267 throw new ArgumentException ("dateTime parameter is an invalid time");
269 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
272 DateTime utc = ConvertTimeToUtc (dateTime);
274 if (destinationTimeZone != TimeZoneInfo.Utc) {
275 utc = ConvertTimeFromUtc (utc, destinationTimeZone);
276 if (dateTime.Kind == DateTimeKind.Unspecified)
277 return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
283 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
285 if (destinationTimeZone == null)
286 throw new ArgumentNullException("destinationTimeZone");
288 var utcDateTime = dateTimeOffset.UtcDateTime;
289 AdjustmentRule rule = destinationTimeZone.GetApplicableRule (utcDateTime);
291 if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
292 var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
293 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
296 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
300 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
302 return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
305 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
307 return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
310 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
312 return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
315 private DateTime ConvertTimeFromUtc (DateTime dateTime)
317 if (dateTime.Kind == DateTimeKind.Local)
318 throw new ArgumentException ("Kind property of dateTime is Local");
320 if (this == TimeZoneInfo.Utc)
321 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
323 //FIXME: do not rely on DateTime implementation !
324 if (this == TimeZoneInfo.Local)
327 return dateTime.ToLocalTime ();
329 return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
334 AdjustmentRule rule = GetApplicableRule (dateTime);
335 if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
336 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
338 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
341 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
343 if (destinationTimeZone == null)
344 throw new ArgumentNullException ("destinationTimeZone");
346 return destinationTimeZone.ConvertTimeFromUtc (dateTime);
349 public static DateTime ConvertTimeToUtc (DateTime dateTime)
351 if (dateTime.Kind == DateTimeKind.Utc)
354 return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local);
357 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
359 if (sourceTimeZone == null)
360 throw new ArgumentNullException ("sourceTimeZone");
362 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
363 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
365 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
366 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
368 if (sourceTimeZone.IsInvalidTime (dateTime))
369 throw new ArgumentException ("dateTime parameter is an invalid time");
371 if (dateTime.Kind == DateTimeKind.Utc)
374 if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
375 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
377 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
379 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
381 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
385 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
387 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
390 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
392 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
395 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
397 return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
401 public override bool Equals (object obj)
403 return Equals (obj as TimeZoneInfo);
407 public bool Equals (TimeZoneInfo other)
412 return other.Id == this.Id && HasSameRules (other);
415 public static TimeZoneInfo FindSystemTimeZoneById (string id)
417 //FIXME: this method should check for cached values in systemTimeZones
419 throw new ArgumentNullException ("id");
421 if (TimeZoneKey != null)
423 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
425 throw new TimeZoneNotFoundException ();
426 return FromRegistryKey(id, key);
430 var timeZoneInfo = AndroidTimeZones.GetTimeZone (id, id);
431 if (timeZoneInfo == null)
432 throw new TimeZoneNotFoundException ();
435 // Local requires special logic that already exists in the Local property (bug #326)
439 using (Stream stream = GetMonoTouchData (id)) {
440 return BuildFromStream (id, stream);
443 string filepath = Path.Combine (TimeZoneDirectory, id);
444 return FindSystemTimeZoneByFileName (id, filepath);
446 throw new NotImplementedException ();
452 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
454 if (!File.Exists (filepath))
455 throw new TimeZoneNotFoundException ();
457 using (FileStream stream = File.OpenRead (filepath)) {
458 return BuildFromStream (id, stream);
462 #if LIBC || MONOTOUCH
463 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
465 private static TimeZoneInfo BuildFromStream (string id, Stream stream)
467 byte [] buffer = new byte [BUFFER_SIZE];
468 int length = stream.Read (buffer, 0, BUFFER_SIZE);
470 if (!ValidTZFile (buffer, length))
471 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
474 return ParseTZBuffer (id, buffer, length);
475 } catch (Exception e) {
476 throw new InvalidTimeZoneException (e.Message);
482 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
484 byte [] reg_tzi = (byte []) key.GetValue ("TZI");
487 throw new InvalidTimeZoneException ();
489 int bias = BitConverter.ToInt32 (reg_tzi, 0);
490 TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
492 string display_name = (string) key.GetValue ("Display");
493 string standard_name = (string) key.GetValue ("Std");
494 string daylight_name = (string) key.GetValue ("Dlt");
496 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
498 RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
499 if (dst_key != null) {
500 int first_year = (int) dst_key.GetValue ("FirstEntry");
501 int last_year = (int) dst_key.GetValue ("LastEntry");
504 for (year=first_year; year<=last_year; year++) {
505 byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
506 if (dst_tzi != null) {
507 int start_year = year == first_year ? 1 : year;
508 int end_year = year == last_year ? 9999 : year;
509 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
514 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
516 return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
519 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
521 //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
522 int daylight_bias = BitConverter.ToInt32 (buffer, 8);
524 int standard_year = BitConverter.ToInt16 (buffer, 12);
525 int standard_month = BitConverter.ToInt16 (buffer, 14);
526 int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
527 int standard_day = BitConverter.ToInt16 (buffer, 18);
528 int standard_hour = BitConverter.ToInt16 (buffer, 20);
529 int standard_minute = BitConverter.ToInt16 (buffer, 22);
530 int standard_second = BitConverter.ToInt16 (buffer, 24);
531 int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
533 int daylight_year = BitConverter.ToInt16 (buffer, 28);
534 int daylight_month = BitConverter.ToInt16 (buffer, 30);
535 int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
536 int daylight_day = BitConverter.ToInt16 (buffer, 34);
537 int daylight_hour = BitConverter.ToInt16 (buffer, 36);
538 int daylight_minute = BitConverter.ToInt16 (buffer, 38);
539 int daylight_second = BitConverter.ToInt16 (buffer, 40);
540 int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
542 if (standard_month == 0 || daylight_month == 0)
546 DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
547 TransitionTime start_transition_time;
549 if (daylight_year == 0) {
550 start_date = new DateTime (start_year, 1, 1);
551 start_transition_time = TransitionTime.CreateFloatingDateRule (
552 start_timeofday, daylight_month, daylight_day,
553 (DayOfWeek) daylight_dayofweek);
556 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
557 daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
558 start_transition_time = TransitionTime.CreateFixedDateRule (
559 start_timeofday, daylight_month, daylight_day);
563 DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
564 TransitionTime end_transition_time;
566 if (standard_year == 0) {
567 end_date = new DateTime (end_year, 12, 31);
568 end_transition_time = TransitionTime.CreateFloatingDateRule (
569 end_timeofday, standard_month, standard_day,
570 (DayOfWeek) standard_dayofweek);
573 end_date = new DateTime (standard_year, standard_month, standard_day,
574 standard_hour, standard_minute, standard_second, standard_millisecond);
575 end_transition_time = TransitionTime.CreateFixedDateRule (
576 end_timeofday, standard_month, standard_day);
579 TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
581 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
582 start_date, end_date, daylight_delta,
583 start_transition_time, end_transition_time));
587 public AdjustmentRule [] GetAdjustmentRules ()
589 if (!supportsDaylightSavingTime)
590 return new AdjustmentRule [0];
592 return (AdjustmentRule []) adjustmentRules.Clone ();
595 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
597 if (!IsAmbiguousTime (dateTime))
598 throw new ArgumentException ("dateTime is not an ambiguous time");
600 AdjustmentRule rule = GetApplicableRule (dateTime);
602 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
604 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
607 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
609 if (!IsAmbiguousTime (dateTimeOffset))
610 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
612 throw new NotImplementedException ();
615 public override int GetHashCode ()
617 int hash_code = Id.GetHashCode ();
618 foreach (AdjustmentRule rule in GetAdjustmentRules ())
619 hash_code ^= rule.GetHashCode ();
624 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
626 public void GetObjectData (SerializationInfo info, StreamingContext context)
630 throw new ArgumentNullException ("info");
631 info.AddValue ("Id", id);
632 info.AddValue ("DisplayName", displayName);
633 info.AddValue ("StandardName", standardDisplayName);
634 info.AddValue ("DaylightName", daylightDisplayName);
635 info.AddValue ("BaseUtcOffset", baseUtcOffset);
636 info.AddValue ("AdjustmentRules", adjustmentRules);
637 info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
640 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
641 private static List<TimeZoneInfo> systemTimeZones;
642 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
644 if (systemTimeZones == null) {
645 systemTimeZones = new List<TimeZoneInfo> ();
647 if (TimeZoneKey != null) {
648 foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
650 systemTimeZones.Add (FindSystemTimeZoneById (id));
654 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
658 foreach (string id in AndroidTimeZones.GetAvailableIds ()) {
659 var tz = AndroidTimeZones.GetTimeZone (id, id);
661 systemTimeZones.Add (tz);
664 if (systemTimeZones.Count == 0) {
665 foreach (string name in GetMonoTouchNames ()) {
666 using (Stream stream = GetMonoTouchData (name, false)) {
669 systemTimeZones.Add (BuildFromStream (name, stream));
674 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
675 foreach (string continent in continents) {
677 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
679 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
680 systemTimeZones.Add (FindSystemTimeZoneById (id));
681 } catch (ArgumentNullException) {
682 } catch (TimeZoneNotFoundException) {
683 } catch (InvalidTimeZoneException) {
684 } catch (Exception) {
691 throw new NotImplementedException ("This method is not implemented for this platform");
694 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
697 public TimeSpan GetUtcOffset (DateTime dateTime)
700 return GetUtcOffset (dateTime, out isDST);
703 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
705 throw new NotImplementedException ();
708 private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST)
712 TimeZoneInfo tz = this;
713 if (dateTime.Kind == DateTimeKind.Utc)
714 tz = TimeZoneInfo.Utc;
716 if (dateTime.Kind == DateTimeKind.Local)
717 tz = TimeZoneInfo.Local;
720 var tzOffset = GetUtcOffset (dateTime, tz, out isTzDst);
727 var utcTicks = dateTime.Ticks - tzOffset.Ticks;
728 if (utcTicks < 0 || utcTicks > DateTime.MaxValue.Ticks)
729 return BaseUtcOffset;
731 var utcDateTime = new DateTime (utcTicks, DateTimeKind.Utc);
733 return GetUtcOffset (utcDateTime, this, out isDST);
736 private static TimeSpan GetUtcOffset (DateTime dateTime, TimeZoneInfo tz, out bool isDST)
738 if (dateTime.Kind == DateTimeKind.Local && tz != TimeZoneInfo.Local)
739 throw new Exception ();
743 if (tz == TimeZoneInfo.Utc)
744 return TimeSpan.Zero;
747 if (tz.TryGetTransitionOffset(dateTime, out offset, out isDST))
750 if (dateTime.Kind == DateTimeKind.Utc) {
751 var utcRule = tz.GetApplicableRule (dateTime);
752 if (utcRule != null && tz.IsInDST (utcRule, dateTime)) {
754 return tz.BaseUtcOffset + utcRule.DaylightDelta;
757 return tz.BaseUtcOffset;
760 var stdTicks = dateTime.Ticks - tz.BaseUtcOffset.Ticks;
761 if (stdTicks < 0 || stdTicks > DateTime.MaxValue.Ticks)
762 return tz.BaseUtcOffset;
764 var stdUtcDateTime = new DateTime (stdTicks, DateTimeKind.Utc);
765 var tzRule = tz.GetApplicableRule (stdUtcDateTime);
767 DateTime dstUtcDateTime = DateTime.MinValue;
768 if (tzRule != null) {
769 var dstTicks = stdUtcDateTime.Ticks - tzRule.DaylightDelta.Ticks;
770 if (dstTicks < 0 || dstTicks > DateTime.MaxValue.Ticks)
771 return tz.BaseUtcOffset;
773 dstUtcDateTime = new DateTime (dstTicks, DateTimeKind.Utc);
776 if (tzRule != null && tz.IsInDST (tzRule, stdUtcDateTime) && tz.IsInDST (tzRule, dstUtcDateTime)) {
778 return tz.BaseUtcOffset + tzRule.DaylightDelta;
781 return tz.BaseUtcOffset;
784 public bool HasSameRules (TimeZoneInfo other)
787 throw new ArgumentNullException ("other");
789 if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
792 if (this.adjustmentRules == null)
795 if (this.BaseUtcOffset != other.BaseUtcOffset)
798 if (this.adjustmentRules.Length != other.adjustmentRules.Length)
801 for (int i = 0; i < adjustmentRules.Length; i++) {
802 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
809 public bool IsAmbiguousTime (DateTime dateTime)
811 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
812 throw new ArgumentException ("Kind is Local and time is Invalid");
814 if (this == TimeZoneInfo.Utc)
817 if (dateTime.Kind == DateTimeKind.Utc)
818 dateTime = ConvertTimeFromUtc (dateTime);
820 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
821 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
823 AdjustmentRule rule = GetApplicableRule (dateTime);
825 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
826 if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
833 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
835 throw new NotImplementedException ();
838 private bool IsInDST (AdjustmentRule rule, DateTime dateTime)
840 // Check whether we're in the dateTime year's DST period
841 if (IsInDSTForYear (rule, dateTime, dateTime.Year))
844 // We might be in the dateTime previous year's DST period
845 return IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
848 bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
850 DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
851 DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
852 if (dateTime.Kind == DateTimeKind.Utc) {
853 DST_start -= BaseUtcOffset;
854 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
857 return (dateTime >= DST_start && dateTime < DST_end);
860 public bool IsDaylightSavingTime (DateTime dateTime)
862 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
863 throw new ArgumentException ("dateTime is invalid and Kind is Local");
865 if (this == TimeZoneInfo.Utc)
868 if (!SupportsDaylightSavingTime)
872 GetUtcOffset (dateTime, out isDst);
877 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
879 throw new NotImplementedException ();
882 public bool IsInvalidTime (DateTime dateTime)
884 if (dateTime.Kind == DateTimeKind.Utc)
886 if (dateTime.Kind == DateTimeKind.Local && this != Local)
889 AdjustmentRule rule = GetApplicableRule (dateTime);
891 DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
892 if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
900 void IDeserializationCallback.OnDeserialization (object sender)
902 public void OnDeserialization (object sender)
906 TimeZoneInfo.Validate (id, baseUtcOffset, adjustmentRules);
907 } catch (ArgumentException ex) {
908 throw new SerializationException ("invalid serialization data", ex);
912 private static void Validate (string id, TimeSpan baseUtcOffset, AdjustmentRule [] adjustmentRules)
915 throw new ArgumentNullException ("id");
917 if (id == String.Empty)
918 throw new ArgumentException ("id parameter is an empty string");
920 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
921 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
923 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
924 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
928 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
931 if (adjustmentRules != null && adjustmentRules.Length != 0) {
932 AdjustmentRule prev = null;
933 foreach (AdjustmentRule current in adjustmentRules) {
935 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
937 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
938 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
939 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;");
941 if (prev != null && prev.DateStart > current.DateStart)
942 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
944 if (prev != null && prev.DateEnd > current.DateStart)
945 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
947 if (prev != null && prev.DateEnd == current.DateStart)
948 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
955 public override string ToString ()
960 private TimeZoneInfo (SerializationInfo info, StreamingContext context)
963 throw new ArgumentNullException ("info");
964 id = (string) info.GetValue ("Id", typeof (string));
965 displayName = (string) info.GetValue ("DisplayName", typeof (string));
966 standardDisplayName = (string) info.GetValue ("StandardName", typeof (string));
967 daylightDisplayName = (string) info.GetValue ("DaylightName", typeof (string));
968 baseUtcOffset = (TimeSpan) info.GetValue ("BaseUtcOffset", typeof (TimeSpan));
969 adjustmentRules = (TimeZoneInfo.AdjustmentRule []) info.GetValue ("AdjustmentRules", typeof (TimeZoneInfo.AdjustmentRule []));
970 supportsDaylightSavingTime = (bool) info.GetValue ("SupportsDaylightSavingTime", typeof (bool));
973 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
976 throw new ArgumentNullException ("id");
978 if (id == String.Empty)
979 throw new ArgumentException ("id parameter is an empty string");
981 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
982 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
984 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
985 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
989 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
992 bool supportsDaylightSavingTime = !disableDaylightSavingTime;
994 if (adjustmentRules != null && adjustmentRules.Length != 0) {
995 AdjustmentRule prev = null;
996 foreach (AdjustmentRule current in adjustmentRules) {
998 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
1000 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
1001 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
1002 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;");
1004 if (prev != null && prev.DateStart > current.DateStart)
1005 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
1007 if (prev != null && prev.DateEnd > current.DateStart)
1008 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
1010 if (prev != null && prev.DateEnd == current.DateStart)
1011 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
1016 supportsDaylightSavingTime = false;
1020 this.baseUtcOffset = baseUtcOffset;
1021 this.displayName = displayName ?? id;
1022 this.standardDisplayName = standardDisplayName ?? id;
1023 this.daylightDisplayName = daylightDisplayName;
1024 this.supportsDaylightSavingTime = supportsDaylightSavingTime;
1025 this.adjustmentRules = adjustmentRules;
1028 private AdjustmentRule GetApplicableRule (DateTime dateTime)
1030 //Transitions are always in standard time
1031 DateTime date = dateTime;
1033 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1034 date = date.ToUniversalTime () + BaseUtcOffset;
1036 if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1037 date = date + BaseUtcOffset;
1039 if (adjustmentRules != null) {
1040 foreach (AdjustmentRule rule in adjustmentRules) {
1041 if (rule.DateStart > date.Date)
1043 if (rule.DateEnd < date.Date)
1051 private bool TryGetTransitionOffset (DateTime dateTime, out TimeSpan offset,out bool isDst)
1053 offset = BaseUtcOffset;
1056 if (transitions == null)
1059 //Transitions are always in standard time
1060 DateTime date = dateTime;
1062 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1063 date = date.ToUniversalTime () + BaseUtcOffset;
1065 if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1066 date = date + BaseUtcOffset;
1068 for (var i = transitions.Count - 1; i >= 0; i--) {
1069 var pair = transitions [i];
1070 DateTime ttime = pair.Key;
1071 TimeType ttype = pair.Value;
1076 offset = new TimeSpan (0, 0, ttype.Offset);
1077 isDst = ttype.IsDst;
1085 private static DateTime TransitionPoint (TransitionTime transition, int year)
1087 if (transition.IsFixedDateRule)
1088 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
1090 DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
1091 int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
1092 if (day > DateTime.DaysInMonth (year, transition.Month))
1096 return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
1099 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
1101 AdjustmentRule prev = null;
1102 foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
1103 if (prev != null && prev.DateEnd > current.DateStart) {
1104 adjustmentRules.Remove (current);
1108 return adjustmentRules;
1111 #if LIBC || MONODROID
1112 private static bool ValidTZFile (byte [] buffer, int length)
1114 StringBuilder magic = new StringBuilder ();
1116 for (int i = 0; i < 4; i++)
1117 magic.Append ((char)buffer [i]);
1119 if (magic.ToString () != "TZif")
1122 if (length >= BUFFER_SIZE)
1128 static int SwapInt32 (int i)
1130 return (((i >> 24) & 0xff)
1131 | ((i >> 8) & 0xff00)
1132 | ((i << 8) & 0xff0000)
1136 static int ReadBigEndianInt32 (byte [] buffer, int start)
1138 int i = BitConverter.ToInt32 (buffer, start);
1139 if (!BitConverter.IsLittleEndian)
1142 return SwapInt32 (i);
1145 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
1147 //Reading the header. 4 bytes for magic, 16 are reserved
1148 int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
1149 int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
1150 int leapcnt = ReadBigEndianInt32 (buffer, 28);
1151 int timecnt = ReadBigEndianInt32 (buffer, 32);
1152 int typecnt = ReadBigEndianInt32 (buffer, 36);
1153 int charcnt = ReadBigEndianInt32 (buffer, 40);
1155 if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
1156 throw new InvalidTimeZoneException ();
1158 Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
1159 Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
1160 List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
1162 if (time_types.Count == 0)
1163 throw new InvalidTimeZoneException ();
1165 if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
1166 throw new InvalidTimeZoneException ();
1168 TimeSpan baseUtcOffset = new TimeSpan (0);
1169 TimeSpan dstDelta = new TimeSpan (0);
1170 string standardDisplayName = null;
1171 string daylightDisplayName = null;
1172 bool dst_observed = false;
1173 DateTime dst_start = DateTime.MinValue;
1174 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
1175 bool storeTransition = false;
1177 for (int i = 0; i < transitions.Count; i++) {
1178 var pair = transitions [i];
1179 DateTime ttime = pair.Key;
1180 TimeType ttype = pair.Value;
1182 if (standardDisplayName != ttype.Name)
1183 standardDisplayName = ttype.Name;
1184 if (baseUtcOffset.TotalSeconds != ttype.Offset) {
1185 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
1186 if (adjustmentRules.Count > 0) // We ignore AdjustmentRules but store transitions.
1187 storeTransition = true;
1188 adjustmentRules = new List<AdjustmentRule> ();
1189 dst_observed = false;
1192 //FIXME: check additional fields for this:
1193 //most of the transitions are expressed in GMT
1194 dst_start += baseUtcOffset;
1195 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
1197 //some weird timezone (America/Phoenix) have end dates on Jan 1st
1198 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
1199 dst_end -= new TimeSpan (24, 0, 0);
1201 DateTime dateStart, dateEnd;
1202 if (dst_start.Month < 7)
1203 dateStart = new DateTime (dst_start.Year, 1, 1);
1205 dateStart = new DateTime (dst_start.Year, 7, 1);
1207 if (dst_end.Month >= 7)
1208 dateEnd = new DateTime (dst_end.Year, 12, 31);
1210 dateEnd = new DateTime (dst_end.Year, 6, 30);
1213 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1214 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1215 if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1216 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1218 dst_observed = false;
1220 if (daylightDisplayName != ttype.Name)
1221 daylightDisplayName = ttype.Name;
1222 if (dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds)
1223 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1226 dst_observed = true;
1231 if (adjustmentRules.Count == 0 && !storeTransition) {
1232 TimeType t = (TimeType)time_types [0];
1233 if (standardDisplayName == null) {
1234 standardDisplayName = t.Name;
1235 baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1237 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1239 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1242 if (storeTransition)
1243 tz.transitions = transitions;
1248 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1250 var abbrevs = new Dictionary<int, string> ();
1251 int abbrev_index = 0;
1252 var sb = new StringBuilder ();
1253 for (int i = 0; i < count; i++) {
1254 char c = (char) buffer [index + i];
1258 abbrevs.Add (abbrev_index, sb.ToString ());
1259 //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1260 for (int j = 1; j < sb.Length; j++)
1261 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1262 abbrev_index = i + 1;
1263 sb = new StringBuilder ();
1269 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1271 var types = new Dictionary<int, TimeType> (count);
1272 for (int i = 0; i < count; i++) {
1273 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1274 byte is_dst = buffer [index + 6 * i + 4];
1275 byte abbrev = buffer [index + 6 * i + 5];
1276 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1281 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1283 var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1284 for (int i = 0; i < count; i++) {
1285 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1286 DateTime ttime = DateTimeFromUnixTime (unixtime);
1287 byte ttype = buffer [index + 4 * count + i];
1288 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1293 static DateTime DateTimeFromUnixTime (long unix_time)
1295 DateTime date_time = new DateTime (1970, 1, 1);
1296 return date_time.AddSeconds (unix_time);
1301 public readonly int Offset;
1302 public readonly bool IsDst;
1305 public TimeType (int offset, bool is_dst, string abbrev)
1307 this.Offset = offset;
1308 this.IsDst = is_dst;
1312 public override string ToString ()
1314 return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;