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 if (IsWindows && LocalZoneKey != null) {
121 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
122 name = TrimSpecial (name);
124 return TimeZoneInfo.FindSystemTimeZoneById (name);
127 var tz = Environment.GetEnvironmentVariable ("TZ");
129 if (tz == String.Empty)
132 return FindSystemTimeZoneByFileName (tz, Path.Combine (TimeZoneDirectory, tz));
139 return FindSystemTimeZoneByFileName ("Local", "/etc/localtime");
142 return FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));
150 string standardDisplayName;
151 public string StandardName {
152 get { return standardDisplayName; }
155 bool supportsDaylightSavingTime;
156 public bool SupportsDaylightSavingTime {
157 get { return supportsDaylightSavingTime; }
160 static TimeZoneInfo utc;
161 public static TimeZoneInfo Utc {
164 utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
169 static string timeZoneDirectory;
170 static string TimeZoneDirectory {
172 if (timeZoneDirectory == null)
173 timeZoneDirectory = "/usr/share/zoneinfo";
174 return timeZoneDirectory;
178 timeZoneDirectory = value;
182 private AdjustmentRule [] adjustmentRules;
186 /// Determine whether windows of not (taken Stephane Delcroix's code)
188 private static bool IsWindows
191 int platform = (int) Environment.OSVersion.Platform;
192 return ((platform != 4) && (platform != 6) && (platform != 128));
197 /// Needed to trim misc garbage in MS registry keys
199 private static string TrimSpecial (string str)
202 while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
203 var Iend = str.Length - 1;
204 while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
206 return str.Substring (Istart, Iend-Istart+1);
209 static RegistryKey timeZoneKey;
210 static RegistryKey TimeZoneKey {
212 if (timeZoneKey != null)
217 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
218 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
223 static RegistryKey localZoneKey;
224 static RegistryKey LocalZoneKey {
226 if (localZoneKey != null)
232 return localZoneKey = Registry.LocalMachine.OpenSubKey (
233 "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
238 public static void ClearCachedData ()
242 systemTimeZones = null;
245 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
247 return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
250 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
252 if (sourceTimeZone == null)
253 throw new ArgumentNullException ("sourceTimeZone");
255 if (destinationTimeZone == null)
256 throw new ArgumentNullException ("destinationTimeZone");
258 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
259 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
261 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
262 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
264 if (sourceTimeZone.IsInvalidTime (dateTime))
265 throw new ArgumentException ("dateTime parameter is an invalid time");
267 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
270 DateTime utc = ConvertTimeToUtc (dateTime);
272 if (destinationTimeZone != TimeZoneInfo.Utc) {
273 utc = ConvertTimeFromUtc (utc, destinationTimeZone);
274 if (dateTime.Kind == DateTimeKind.Unspecified)
275 return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
281 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
283 if (destinationTimeZone == null)
284 throw new ArgumentNullException("destinationTimeZone");
286 var utcDateTime = dateTimeOffset.UtcDateTime;
287 AdjustmentRule rule = destinationTimeZone.GetApplicableRule (utcDateTime);
289 if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
290 var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
291 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
294 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
298 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
300 return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
303 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
305 return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
308 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
310 return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
313 private DateTime ConvertTimeFromUtc (DateTime dateTime)
315 if (dateTime.Kind == DateTimeKind.Local)
316 throw new ArgumentException ("Kind property of dateTime is Local");
318 if (this == TimeZoneInfo.Utc)
319 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
321 //FIXME: do not rely on DateTime implementation !
322 if (this == TimeZoneInfo.Local)
325 return dateTime.ToLocalTime ();
327 return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
332 AdjustmentRule rule = GetApplicableRule (dateTime);
333 if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
334 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
336 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
339 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
341 if (destinationTimeZone == null)
342 throw new ArgumentNullException ("destinationTimeZone");
344 return destinationTimeZone.ConvertTimeFromUtc (dateTime);
347 public static DateTime ConvertTimeToUtc (DateTime dateTime)
349 if (dateTime.Kind == DateTimeKind.Utc)
352 return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local);
355 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
357 if (sourceTimeZone == null)
358 throw new ArgumentNullException ("sourceTimeZone");
360 if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
361 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
363 if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
364 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
366 if (sourceTimeZone.IsInvalidTime (dateTime))
367 throw new ArgumentException ("dateTime parameter is an invalid time");
369 if (dateTime.Kind == DateTimeKind.Utc)
372 if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
373 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
375 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
377 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
379 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
383 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName)
385 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
388 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
390 return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
393 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
395 return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
399 public override bool Equals (object obj)
401 return Equals (obj as TimeZoneInfo);
405 public bool Equals (TimeZoneInfo other)
410 return other.Id == this.Id && HasSameRules (other);
413 public static TimeZoneInfo FindSystemTimeZoneById (string id)
415 //FIXME: this method should check for cached values in systemTimeZones
417 throw new ArgumentNullException ("id");
419 if (TimeZoneKey != null)
421 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
423 throw new TimeZoneNotFoundException ();
424 return FromRegistryKey(id, key);
427 // Local requires special logic that already exists in the Local property (bug #326)
431 using (Stream stream = GetMonoTouchData (id)) {
432 return BuildFromStream (id, stream);
435 var timeZoneInfo = AndroidTimeZones.GetTimeZone (id, id);
436 if (timeZoneInfo == null)
437 throw new TimeZoneNotFoundException ();
440 string filepath = Path.Combine (TimeZoneDirectory, id);
441 return FindSystemTimeZoneByFileName (id, filepath);
443 throw new NotImplementedException ();
448 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
450 if (!File.Exists (filepath))
451 throw new TimeZoneNotFoundException ();
453 using (FileStream stream = File.OpenRead (filepath)) {
454 return BuildFromStream (id, stream);
458 #if LIBC || MONOTOUCH
459 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
461 private static TimeZoneInfo BuildFromStream (string id, Stream stream)
463 byte [] buffer = new byte [BUFFER_SIZE];
464 int length = stream.Read (buffer, 0, BUFFER_SIZE);
466 if (!ValidTZFile (buffer, length))
467 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
470 return ParseTZBuffer (id, buffer, length);
471 } catch (Exception e) {
472 throw new InvalidTimeZoneException (e.Message);
478 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
480 byte [] reg_tzi = (byte []) key.GetValue ("TZI");
483 throw new InvalidTimeZoneException ();
485 int bias = BitConverter.ToInt32 (reg_tzi, 0);
486 TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
488 string display_name = (string) key.GetValue ("Display");
489 string standard_name = (string) key.GetValue ("Std");
490 string daylight_name = (string) key.GetValue ("Dlt");
492 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
494 RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
495 if (dst_key != null) {
496 int first_year = (int) dst_key.GetValue ("FirstEntry");
497 int last_year = (int) dst_key.GetValue ("LastEntry");
500 for (year=first_year; year<=last_year; year++) {
501 byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
502 if (dst_tzi != null) {
503 int start_year = year == first_year ? 1 : year;
504 int end_year = year == last_year ? 9999 : year;
505 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
510 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
512 return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
515 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
517 //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
518 int daylight_bias = BitConverter.ToInt32 (buffer, 8);
520 int standard_year = BitConverter.ToInt16 (buffer, 12);
521 int standard_month = BitConverter.ToInt16 (buffer, 14);
522 int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
523 int standard_day = BitConverter.ToInt16 (buffer, 18);
524 int standard_hour = BitConverter.ToInt16 (buffer, 20);
525 int standard_minute = BitConverter.ToInt16 (buffer, 22);
526 int standard_second = BitConverter.ToInt16 (buffer, 24);
527 int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
529 int daylight_year = BitConverter.ToInt16 (buffer, 28);
530 int daylight_month = BitConverter.ToInt16 (buffer, 30);
531 int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
532 int daylight_day = BitConverter.ToInt16 (buffer, 34);
533 int daylight_hour = BitConverter.ToInt16 (buffer, 36);
534 int daylight_minute = BitConverter.ToInt16 (buffer, 38);
535 int daylight_second = BitConverter.ToInt16 (buffer, 40);
536 int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
538 if (standard_month == 0 || daylight_month == 0)
542 DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
543 TransitionTime start_transition_time;
545 if (daylight_year == 0) {
546 start_date = new DateTime (start_year, 1, 1);
547 start_transition_time = TransitionTime.CreateFloatingDateRule (
548 start_timeofday, daylight_month, daylight_day,
549 (DayOfWeek) daylight_dayofweek);
552 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
553 daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
554 start_transition_time = TransitionTime.CreateFixedDateRule (
555 start_timeofday, daylight_month, daylight_day);
559 DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
560 TransitionTime end_transition_time;
562 if (standard_year == 0) {
563 end_date = new DateTime (end_year, 12, 31);
564 end_transition_time = TransitionTime.CreateFloatingDateRule (
565 end_timeofday, standard_month, standard_day,
566 (DayOfWeek) standard_dayofweek);
569 end_date = new DateTime (standard_year, standard_month, standard_day,
570 standard_hour, standard_minute, standard_second, standard_millisecond);
571 end_transition_time = TransitionTime.CreateFixedDateRule (
572 end_timeofday, standard_month, standard_day);
575 TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
577 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
578 start_date, end_date, daylight_delta,
579 start_transition_time, end_transition_time));
583 public AdjustmentRule [] GetAdjustmentRules ()
585 if (!supportsDaylightSavingTime)
586 return new AdjustmentRule [0];
588 return (AdjustmentRule []) adjustmentRules.Clone ();
591 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
593 if (!IsAmbiguousTime (dateTime))
594 throw new ArgumentException ("dateTime is not an ambiguous time");
596 AdjustmentRule rule = GetApplicableRule (dateTime);
598 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
600 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
603 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
605 if (!IsAmbiguousTime (dateTimeOffset))
606 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
608 throw new NotImplementedException ();
611 public override int GetHashCode ()
613 int hash_code = Id.GetHashCode ();
614 foreach (AdjustmentRule rule in GetAdjustmentRules ())
615 hash_code ^= rule.GetHashCode ();
620 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
622 public void GetObjectData (SerializationInfo info, StreamingContext context)
626 throw new ArgumentNullException ("info");
627 info.AddValue ("Id", id);
628 info.AddValue ("DisplayName", displayName);
629 info.AddValue ("StandardName", standardDisplayName);
630 info.AddValue ("DaylightName", daylightDisplayName);
631 info.AddValue ("BaseUtcOffset", baseUtcOffset);
632 info.AddValue ("AdjustmentRules", adjustmentRules);
633 info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
636 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
637 private static List<TimeZoneInfo> systemTimeZones;
638 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
640 if (systemTimeZones == null) {
641 systemTimeZones = new List<TimeZoneInfo> ();
643 if (TimeZoneKey != null) {
644 foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
646 systemTimeZones.Add (FindSystemTimeZoneById (id));
650 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
654 foreach (string id in AndroidTimeZones.GetAvailableIds ()) {
655 var tz = AndroidTimeZones.GetTimeZone (id, id);
657 systemTimeZones.Add (tz);
660 if (systemTimeZones.Count == 0) {
661 foreach (string name in GetMonoTouchNames ()) {
662 using (Stream stream = GetMonoTouchData (name, false)) {
665 systemTimeZones.Add (BuildFromStream (name, stream));
670 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
671 foreach (string continent in continents) {
673 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
675 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
676 systemTimeZones.Add (FindSystemTimeZoneById (id));
677 } catch (ArgumentNullException) {
678 } catch (TimeZoneNotFoundException) {
679 } catch (InvalidTimeZoneException) {
680 } catch (Exception) {
687 throw new NotImplementedException ("This method is not implemented for this platform");
690 return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
693 public TimeSpan GetUtcOffset (DateTime dateTime)
696 return GetUtcOffset (dateTime, out isDST);
699 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
701 throw new NotImplementedException ();
704 private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST)
708 TimeZoneInfo tz = this;
709 if (dateTime.Kind == DateTimeKind.Utc)
710 tz = TimeZoneInfo.Utc;
712 if (dateTime.Kind == DateTimeKind.Local)
713 tz = TimeZoneInfo.Local;
716 var tzOffset = GetUtcOffset (dateTime, tz, out isTzDst);
723 var utcTicks = dateTime.Ticks - tzOffset.Ticks;
724 if (utcTicks < 0 || utcTicks > DateTime.MaxValue.Ticks)
725 return BaseUtcOffset;
727 var utcDateTime = new DateTime (utcTicks, DateTimeKind.Utc);
729 return GetUtcOffset (utcDateTime, this, out isDST);
732 private static TimeSpan GetUtcOffset (DateTime dateTime, TimeZoneInfo tz, out bool isDST)
734 if (dateTime.Kind == DateTimeKind.Local && tz != TimeZoneInfo.Local)
735 throw new Exception ();
739 if (tz == TimeZoneInfo.Utc)
740 return TimeSpan.Zero;
743 if (tz.TryGetTransitionOffset(dateTime, out offset, out isDST))
746 if (dateTime.Kind == DateTimeKind.Utc) {
747 var utcRule = tz.GetApplicableRule (dateTime);
748 if (utcRule != null && tz.IsInDST (utcRule, dateTime)) {
750 return tz.BaseUtcOffset + utcRule.DaylightDelta;
753 return tz.BaseUtcOffset;
756 var stdTicks = dateTime.Ticks - tz.BaseUtcOffset.Ticks;
757 if (stdTicks < 0 || stdTicks > DateTime.MaxValue.Ticks)
758 return tz.BaseUtcOffset;
760 var stdUtcDateTime = new DateTime (stdTicks, DateTimeKind.Utc);
761 var tzRule = tz.GetApplicableRule (stdUtcDateTime);
763 DateTime dstUtcDateTime = DateTime.MinValue;
764 if (tzRule != null) {
765 var dstTicks = stdUtcDateTime.Ticks - tzRule.DaylightDelta.Ticks;
766 if (dstTicks < 0 || dstTicks > DateTime.MaxValue.Ticks)
767 return tz.BaseUtcOffset;
769 dstUtcDateTime = new DateTime (dstTicks, DateTimeKind.Utc);
772 if (tzRule != null && tz.IsInDST (tzRule, stdUtcDateTime) && tz.IsInDST (tzRule, dstUtcDateTime)) {
774 return tz.BaseUtcOffset + tzRule.DaylightDelta;
777 return tz.BaseUtcOffset;
780 public bool HasSameRules (TimeZoneInfo other)
783 throw new ArgumentNullException ("other");
785 if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
788 if (this.adjustmentRules == null)
791 if (this.BaseUtcOffset != other.BaseUtcOffset)
794 if (this.adjustmentRules.Length != other.adjustmentRules.Length)
797 for (int i = 0; i < adjustmentRules.Length; i++) {
798 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
805 public bool IsAmbiguousTime (DateTime dateTime)
807 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
808 throw new ArgumentException ("Kind is Local and time is Invalid");
810 if (this == TimeZoneInfo.Utc)
813 if (dateTime.Kind == DateTimeKind.Utc)
814 dateTime = ConvertTimeFromUtc (dateTime);
816 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
817 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
819 AdjustmentRule rule = GetApplicableRule (dateTime);
821 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
822 if (dateTime > tpoint - rule.DaylightDelta && dateTime <= tpoint)
829 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
831 throw new NotImplementedException ();
834 private bool IsInDST (AdjustmentRule rule, DateTime dateTime)
836 // Check whether we're in the dateTime year's DST period
837 if (IsInDSTForYear (rule, dateTime, dateTime.Year))
840 // We might be in the dateTime previous year's DST period
841 return IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
844 bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
846 DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
847 DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
848 if (dateTime.Kind == DateTimeKind.Utc) {
849 DST_start -= BaseUtcOffset;
850 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
853 return (dateTime >= DST_start && dateTime < DST_end);
856 public bool IsDaylightSavingTime (DateTime dateTime)
858 if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
859 throw new ArgumentException ("dateTime is invalid and Kind is Local");
861 if (this == TimeZoneInfo.Utc)
864 if (!SupportsDaylightSavingTime)
868 GetUtcOffset (dateTime, out isDst);
873 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
875 throw new NotImplementedException ();
878 public bool IsInvalidTime (DateTime dateTime)
880 if (dateTime.Kind == DateTimeKind.Utc)
882 if (dateTime.Kind == DateTimeKind.Local && this != Local)
885 AdjustmentRule rule = GetApplicableRule (dateTime);
887 DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
888 if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
896 void IDeserializationCallback.OnDeserialization (object sender)
898 public void OnDeserialization (object sender)
902 TimeZoneInfo.Validate (id, baseUtcOffset, adjustmentRules);
903 } catch (ArgumentException ex) {
904 throw new SerializationException ("invalid serialization data", ex);
908 private static void Validate (string id, TimeSpan baseUtcOffset, AdjustmentRule [] adjustmentRules)
911 throw new ArgumentNullException ("id");
913 if (id == String.Empty)
914 throw new ArgumentException ("id parameter is an empty string");
916 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
917 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
919 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
920 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
924 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
927 if (adjustmentRules != null && adjustmentRules.Length != 0) {
928 AdjustmentRule prev = null;
929 foreach (AdjustmentRule current in adjustmentRules) {
931 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
933 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
934 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
935 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;");
937 if (prev != null && prev.DateStart > current.DateStart)
938 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
940 if (prev != null && prev.DateEnd > current.DateStart)
941 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
943 if (prev != null && prev.DateEnd == current.DateStart)
944 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
951 public override string ToString ()
956 private TimeZoneInfo (SerializationInfo info, StreamingContext context)
959 throw new ArgumentNullException ("info");
960 id = (string) info.GetValue ("Id", typeof (string));
961 displayName = (string) info.GetValue ("DisplayName", typeof (string));
962 standardDisplayName = (string) info.GetValue ("StandardName", typeof (string));
963 daylightDisplayName = (string) info.GetValue ("DaylightName", typeof (string));
964 baseUtcOffset = (TimeSpan) info.GetValue ("BaseUtcOffset", typeof (TimeSpan));
965 adjustmentRules = (TimeZoneInfo.AdjustmentRule []) info.GetValue ("AdjustmentRules", typeof (TimeZoneInfo.AdjustmentRule []));
966 supportsDaylightSavingTime = (bool) info.GetValue ("SupportsDaylightSavingTime", typeof (bool));
969 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
972 throw new ArgumentNullException ("id");
974 if (id == String.Empty)
975 throw new ArgumentException ("id parameter is an empty string");
977 if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
978 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
980 if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
981 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
985 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
988 bool supportsDaylightSavingTime = !disableDaylightSavingTime;
990 if (adjustmentRules != null && adjustmentRules.Length != 0) {
991 AdjustmentRule prev = null;
992 foreach (AdjustmentRule current in adjustmentRules) {
994 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
996 if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
997 (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
998 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;");
1000 if (prev != null && prev.DateStart > current.DateStart)
1001 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
1003 if (prev != null && prev.DateEnd > current.DateStart)
1004 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
1006 if (prev != null && prev.DateEnd == current.DateStart)
1007 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
1012 supportsDaylightSavingTime = false;
1016 this.baseUtcOffset = baseUtcOffset;
1017 this.displayName = displayName ?? id;
1018 this.standardDisplayName = standardDisplayName ?? id;
1019 this.daylightDisplayName = daylightDisplayName;
1020 this.supportsDaylightSavingTime = supportsDaylightSavingTime;
1021 this.adjustmentRules = adjustmentRules;
1024 private AdjustmentRule GetApplicableRule (DateTime dateTime)
1026 //Transitions are always in standard time
1027 DateTime date = dateTime;
1029 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1030 date = date.ToUniversalTime () + BaseUtcOffset;
1032 if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1033 date = date + BaseUtcOffset;
1035 if (adjustmentRules != null) {
1036 foreach (AdjustmentRule rule in adjustmentRules) {
1037 if (rule.DateStart > date.Date)
1039 if (rule.DateEnd < date.Date)
1047 private bool TryGetTransitionOffset (DateTime dateTime, out TimeSpan offset,out bool isDst)
1049 offset = BaseUtcOffset;
1052 if (transitions == null)
1055 //Transitions are always in standard time
1056 DateTime date = dateTime;
1058 if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1059 date = date.ToUniversalTime () + BaseUtcOffset;
1061 if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1062 date = date + BaseUtcOffset;
1064 for (var i = transitions.Count - 1; i >= 0; i--) {
1065 var pair = transitions [i];
1066 DateTime ttime = pair.Key;
1067 TimeType ttype = pair.Value;
1072 offset = new TimeSpan (0, 0, ttype.Offset);
1073 isDst = ttype.IsDst;
1081 private static DateTime TransitionPoint (TransitionTime transition, int year)
1083 if (transition.IsFixedDateRule)
1084 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
1086 DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
1087 int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
1088 if (day > DateTime.DaysInMonth (year, transition.Month))
1092 return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
1095 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
1097 AdjustmentRule prev = null;
1098 foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
1099 if (prev != null && prev.DateEnd > current.DateStart) {
1100 adjustmentRules.Remove (current);
1104 return adjustmentRules;
1107 #if LIBC || MONODROID
1108 private static bool ValidTZFile (byte [] buffer, int length)
1110 StringBuilder magic = new StringBuilder ();
1112 for (int i = 0; i < 4; i++)
1113 magic.Append ((char)buffer [i]);
1115 if (magic.ToString () != "TZif")
1118 if (length >= BUFFER_SIZE)
1124 static int SwapInt32 (int i)
1126 return (((i >> 24) & 0xff)
1127 | ((i >> 8) & 0xff00)
1128 | ((i << 8) & 0xff0000)
1132 static int ReadBigEndianInt32 (byte [] buffer, int start)
1134 int i = BitConverter.ToInt32 (buffer, start);
1135 if (!BitConverter.IsLittleEndian)
1138 return SwapInt32 (i);
1141 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
1143 //Reading the header. 4 bytes for magic, 16 are reserved
1144 int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
1145 int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
1146 int leapcnt = ReadBigEndianInt32 (buffer, 28);
1147 int timecnt = ReadBigEndianInt32 (buffer, 32);
1148 int typecnt = ReadBigEndianInt32 (buffer, 36);
1149 int charcnt = ReadBigEndianInt32 (buffer, 40);
1151 if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
1152 throw new InvalidTimeZoneException ();
1154 Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
1155 Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
1156 List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
1158 if (time_types.Count == 0)
1159 throw new InvalidTimeZoneException ();
1161 if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
1162 throw new InvalidTimeZoneException ();
1164 TimeSpan baseUtcOffset = new TimeSpan (0);
1165 TimeSpan dstDelta = new TimeSpan (0);
1166 string standardDisplayName = null;
1167 string daylightDisplayName = null;
1168 bool dst_observed = false;
1169 DateTime dst_start = DateTime.MinValue;
1170 List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
1171 bool storeTransition = false;
1173 for (int i = 0; i < transitions.Count; i++) {
1174 var pair = transitions [i];
1175 DateTime ttime = pair.Key;
1176 TimeType ttype = pair.Value;
1178 if (standardDisplayName != ttype.Name)
1179 standardDisplayName = ttype.Name;
1180 if (baseUtcOffset.TotalSeconds != ttype.Offset) {
1181 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
1182 if (adjustmentRules.Count > 0) // We ignore AdjustmentRules but store transitions.
1183 storeTransition = true;
1184 adjustmentRules = new List<AdjustmentRule> ();
1185 dst_observed = false;
1188 //FIXME: check additional fields for this:
1189 //most of the transitions are expressed in GMT
1190 dst_start += baseUtcOffset;
1191 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
1193 //some weird timezone (America/Phoenix) have end dates on Jan 1st
1194 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
1195 dst_end -= new TimeSpan (24, 0, 0);
1197 DateTime dateStart, dateEnd;
1198 if (dst_start.Month < 7)
1199 dateStart = new DateTime (dst_start.Year, 1, 1);
1201 dateStart = new DateTime (dst_start.Year, 7, 1);
1203 if (dst_end.Month >= 7)
1204 dateEnd = new DateTime (dst_end.Year, 12, 31);
1206 dateEnd = new DateTime (dst_end.Year, 6, 30);
1209 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1210 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1211 if (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1212 adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1214 dst_observed = false;
1216 if (daylightDisplayName != ttype.Name)
1217 daylightDisplayName = ttype.Name;
1218 if (dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds)
1219 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1222 dst_observed = true;
1227 if (adjustmentRules.Count == 0 && !storeTransition) {
1228 TimeType t = (TimeType)time_types [0];
1229 if (standardDisplayName == null) {
1230 standardDisplayName = t.Name;
1231 baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1233 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1235 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1238 if (storeTransition)
1239 tz.transitions = transitions;
1244 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1246 var abbrevs = new Dictionary<int, string> ();
1247 int abbrev_index = 0;
1248 var sb = new StringBuilder ();
1249 for (int i = 0; i < count; i++) {
1250 char c = (char) buffer [index + i];
1254 abbrevs.Add (abbrev_index, sb.ToString ());
1255 //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1256 for (int j = 1; j < sb.Length; j++)
1257 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1258 abbrev_index = i + 1;
1259 sb = new StringBuilder ();
1265 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1267 var types = new Dictionary<int, TimeType> (count);
1268 for (int i = 0; i < count; i++) {
1269 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1270 byte is_dst = buffer [index + 6 * i + 4];
1271 byte abbrev = buffer [index + 6 * i + 5];
1272 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1277 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1279 var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1280 for (int i = 0; i < count; i++) {
1281 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1282 DateTime ttime = DateTimeFromUnixTime (unixtime);
1283 byte ttype = buffer [index + 4 * count + i];
1284 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1289 static DateTime DateTimeFromUnixTime (long unix_time)
1291 DateTime date_time = new DateTime (1970, 1, 1);
1292 return date_time.AddSeconds (unix_time);
1297 public readonly int Offset;
1298 public readonly bool IsDst;
1301 public TimeType (int offset, bool is_dst, string abbrev)
1303 this.Offset = offset;
1304 this.IsDst = is_dst;
1308 public override string ToString ()
1310 return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;