5 // Duncan Mak (duncan@ximian.com)
6 // Ajay Kumar Dwivedi (adwiv@yahoo.com)
7 // Martin Baulig (martin@gnome.org)
10 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
11 // Copyright 2011 Xamarin Inc.
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 // Rewrite ToLocalTime to use GetLocalTimeDiff(DateTime,TimeSpan),
36 // this should only leave the validation at the beginning (for MaxValue)
37 // and then call the helper function. This would remove all the
38 // ifdefs in that code, and replace it with only one, for the construction
41 // Rewrite ToUniversalTime to use a similar setup to that
43 using System.Collections.Generic;
44 using System.Globalization;
45 using System.Runtime.CompilerServices;
46 using System.Runtime.Serialization;
47 using System.Runtime.InteropServices;
53 public abstract class TimeZone
56 static TimeZone currentTimeZone;
59 static object tz_lock = new object ();
61 static long timezone_check;
69 public static TimeZone CurrentTimeZone {
71 long now = DateTime.UtcNow.Ticks;
72 TimeZone tz = currentTimeZone;
75 if (tz == null || Math.Abs (now - timezone_check) > TimeSpan.TicksPerMinute) {
77 tz = AndroidPlatform.GetCurrentSystemTimeZone ();
80 tz = new CurrentSystemTimeZone (now);
91 public abstract string DaylightName {
95 public abstract string StandardName {
100 public abstract DaylightTime GetDaylightChanges (int year);
102 public abstract TimeSpan GetUtcOffset (DateTime time);
104 public virtual bool IsDaylightSavingTime (DateTime time)
106 return IsDaylightSavingTime (time, GetDaylightChanges (time.Year));
109 public static bool IsDaylightSavingTime (DateTime time, DaylightTime daylightTimes)
111 if (daylightTimes == null)
112 throw new ArgumentNullException ("daylightTimes");
114 // If Start == End, then DST is off
115 if (daylightTimes.Start.Ticks == daylightTimes.End.Ticks)
118 //We are in the northern hemisphere.
119 if (daylightTimes.Start.Ticks < daylightTimes.End.Ticks) {
120 if (daylightTimes.Start.Ticks < time.Ticks && daylightTimes.End.Ticks > time.Ticks)
121 return true; // time lies between Start and End
124 else { // We are in the southern hemisphere.
125 if (time.Year == daylightTimes.Start.Year && time.Year == daylightTimes.End.Year)
126 if (time.Ticks < daylightTimes.End.Ticks || time.Ticks > daylightTimes.Start.Ticks)
127 return true; // time is less than End OR more than Start
133 public virtual DateTime ToLocalTime (DateTime time)
135 if (time.Kind == DateTimeKind.Local)
138 TimeSpan utcOffset = GetUtcOffset (new DateTime (time.Ticks));
139 if (utcOffset.Ticks > 0) {
140 if (DateTime.MaxValue - utcOffset < time)
141 return DateTime.SpecifyKind (DateTime.MaxValue, DateTimeKind.Local);
142 } else if (utcOffset.Ticks < 0) {
143 if (time.Ticks + utcOffset.Ticks < DateTime.MinValue.Ticks)
144 return DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Local);
147 return DateTime.SpecifyKind (time.Add (utcOffset), DateTimeKind.Local);
150 public virtual DateTime ToUniversalTime (DateTime time)
152 if (time.Kind == DateTimeKind.Utc)
155 TimeSpan offset = GetUtcOffset (time);
157 if (offset.Ticks < 0) {
158 if (DateTime.MaxValue + offset < time)
159 return DateTime.SpecifyKind (DateTime.MaxValue, DateTimeKind.Utc);
160 } else if (offset.Ticks > 0) {
161 if (DateTime.MinValue + offset > time)
162 return DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);
165 return DateTime.SpecifyKind (new DateTime (time.Ticks - offset.Ticks), DateTimeKind.Utc);
168 internal static void ClearCachedData ()
170 currentTimeZone = null;
174 // This routine returns the TimeDiff that would have to be
175 // added to "time" to turn it into a local time. This would
176 // be equivalent to call ToLocalTime.
178 // There is one important consideration:
180 // This information is only valid during the minute it
183 // This only works with a real time, not one of the boundary
184 // cases like DateTime.MaxValue, so validation must be done
187 // This is intended to be used by DateTime.Now
189 // We use a minute, just to be conservative and cope with
190 // any potential time zones that might be defined in the future
191 // that might not nicely fit in hour or half-hour steps.
193 internal TimeSpan GetLocalTimeDiff (DateTime time)
195 return GetLocalTimeDiff (time, GetUtcOffset (time));
199 // This routine is intended to be called by GetLocalTimeDiff(DatetTime)
200 // or by ToLocalTime after validation has been performed
202 // time is the time to map, utc_offset is the utc_offset that
203 // has been computed for calling GetUtcOffset on time.
205 // When called by GetLocalTime, utc_offset is assumed to come
206 // from a time constructed by new DateTime (DateTime.GetNow ()), that
209 // When called by ToLocalTime ranges are checked before this is
212 internal TimeSpan GetLocalTimeDiff (DateTime time, TimeSpan utc_offset)
214 DaylightTime dlt = GetDaylightChanges (time.Year);
216 if (dlt.Delta.Ticks == 0)
219 DateTime local = time.Add (utc_offset);
220 if (local < dlt.End && dlt.End.Subtract (dlt.Delta) <= local)
223 if (local >= dlt.Start && dlt.Start.Add (dlt.Delta) > local)
224 return utc_offset - dlt.Delta;
226 return GetUtcOffset (local);
231 internal class CurrentSystemTimeZone : TimeZone, IDeserializationCallback {
234 private string m_standardName;
235 private string m_daylightName;
237 // A yearwise cache of DaylightTime.
238 private Dictionary<int, DaylightTime> m_CachedDaylightChanges = new Dictionary<int, DaylightTime> (1);
240 internal enum TimeZoneData
242 DaylightSavingStartIdx,
243 DaylightSavingEndIdx,
245 AdditionalDaylightOffsetIdx
248 internal enum TimeZoneNames
254 // Internal method to get timezone data.
255 // data[0]: start of daylight saving time (in DateTime ticks).
256 // data[1]: end of daylight saving time (in DateTime ticks).
257 // data[2]: utcoffset (in TimeSpan ticks).
258 // data[3]: additional offset when daylight saving (in TimeSpan ticks).
259 // name[0]: name of this timezone when not daylight saving.
260 // name[1]: name of this timezone when daylight saving.
261 [MethodImplAttribute(MethodImplOptions.InternalCall)]
262 private static extern bool GetTimeZoneData (int year, out Int64[] data, out string[] names);
265 internal CurrentSystemTimeZone ()
270 // Initialized by the constructor
272 static int this_year;
273 static DaylightTime this_year_dlt;
276 // The "lnow" parameter must be the current time, I could have moved
277 // the code here, but I do not want to interfere with serialization
278 // which is why I kept the other constructor around
280 internal CurrentSystemTimeZone (long lnow)
285 DateTime now = new DateTime (lnow);
286 if (!GetTimeZoneData (now.Year, out data, out names))
287 throw new NotSupportedException (Locale.GetText ("Can't get timezone name."));
289 m_standardName = Locale.GetText (names[(int)TimeZoneNames.StandardNameIdx]);
290 m_daylightName = Locale.GetText (names[(int)TimeZoneNames.DaylightNameIdx]);
292 DaylightTime dlt = GetDaylightTimeFromData (data);
293 m_CachedDaylightChanges.Add (now.Year, dlt);
294 OnDeserialization (dlt);
298 public override string DaylightName {
299 get { return m_daylightName; }
302 public override string StandardName {
303 get { return m_standardName; }
307 public override DaylightTime GetDaylightChanges (int year)
309 if (year < 1 || year > 9999)
310 throw new ArgumentOutOfRangeException ("year", year +
311 Locale.GetText (" is not in a range between 1 and 9999."));
314 // First we try the case for this year, very common, and is used
315 // by DateTime.Now (a popular call) indirectly.
317 if (year == this_year)
318 return this_year_dlt;
320 lock (m_CachedDaylightChanges) {
322 if (!m_CachedDaylightChanges.TryGetValue (year, out dlt)) {
326 if (!GetTimeZoneData (year, out data, out names))
327 throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + year));
329 dlt = GetDaylightTimeFromData (data);
330 m_CachedDaylightChanges.Add (year, dlt);
336 public override TimeSpan GetUtcOffset (DateTime time)
338 if (time.Kind == DateTimeKind.Utc)
339 return TimeSpan.Zero;
341 return TimeZoneInfo.Local.GetUtcOffset (time);
344 void IDeserializationCallback.OnDeserialization (object sender)
346 OnDeserialization (null);
349 private void OnDeserialization (DaylightTime dlt)
355 this_year = DateTime.Now.Year;
356 if (!GetTimeZoneData (this_year, out data, out names))
357 throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + this_year));
358 dlt = GetDaylightTimeFromData (data);
360 this_year = dlt.Start.Year;
365 private DaylightTime GetDaylightTimeFromData (long[] data)
367 return new DaylightTime (new DateTime (data[(int)TimeZoneData.DaylightSavingStartIdx]),
368 new DateTime (data[(int)TimeZoneData.DaylightSavingEndIdx]),
369 new TimeSpan (data[(int)TimeZoneData.AdditionalDaylightOffsetIdx]));