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;
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.GetNow ();
75 if (currentTimeZone == null || (now - timezone_check) > TimeSpan.TicksPerMinute) {
76 currentTimeZone = new CurrentSystemTimeZone (now);
87 public abstract string DaylightName {
91 public abstract string StandardName {
96 public abstract DaylightTime GetDaylightChanges (int year);
98 public abstract TimeSpan GetUtcOffset (DateTime time);
100 public virtual bool IsDaylightSavingTime (DateTime time)
102 return IsDaylightSavingTime (time, GetDaylightChanges (time.Year));
105 public static bool IsDaylightSavingTime (DateTime time, DaylightTime daylightTimes)
107 if (daylightTimes == null)
108 throw new ArgumentNullException ("daylightTimes");
110 // If Start == End, then DST is off
111 if (daylightTimes.Start.Ticks == daylightTimes.End.Ticks)
114 //We are in the northern hemisphere.
115 if (daylightTimes.Start.Ticks < daylightTimes.End.Ticks) {
116 if (daylightTimes.Start.Ticks < time.Ticks && daylightTimes.End.Ticks > time.Ticks)
117 return true; // time lies between Start and End
120 else { // We are in the southern hemisphere.
121 if (time.Year == daylightTimes.Start.Year && time.Year == daylightTimes.End.Year)
122 if (time.Ticks < daylightTimes.End.Ticks || time.Ticks > daylightTimes.Start.Ticks)
123 return true; // time is less than End OR more than Start
129 public virtual DateTime ToLocalTime (DateTime time)
131 if (time.Kind == DateTimeKind.Local)
134 TimeSpan utcOffset = GetUtcOffset (new DateTime (time.Ticks));
135 if (utcOffset.Ticks > 0) {
136 if (DateTime.MaxValue - utcOffset < time)
137 return DateTime.SpecifyKind (DateTime.MaxValue, DateTimeKind.Local);
138 } else if (utcOffset.Ticks < 0) {
139 if (time.Ticks + utcOffset.Ticks < DateTime.MinValue.Ticks)
140 return DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Local);
143 DateTime local = DateTime.SpecifyKind (time.Add (utcOffset), DateTimeKind.Local);
144 DaylightTime dlt = GetDaylightChanges (time.Year);
145 if (dlt.Delta.Ticks == 0)
146 return DateTime.SpecifyKind (local, DateTimeKind.Local);
148 // FIXME: check all of the combination of
149 // - basis: local-based or UTC-based
150 // - hemisphere: Northern or Southern
151 // - offset: positive or negative
153 // PST should work fine here.
154 if (local < dlt.End && dlt.End.Subtract (dlt.Delta) <= local)
155 return DateTime.SpecifyKind (local, DateTimeKind.Local);
157 TimeSpan localOffset = GetUtcOffset (local);
158 return DateTime.SpecifyKind (time.Add (localOffset), DateTimeKind.Local);
161 public virtual DateTime ToUniversalTime (DateTime time)
163 if (time.Kind == DateTimeKind.Utc)
166 TimeSpan offset = GetUtcOffset (time);
168 if (offset.Ticks < 0) {
169 if (DateTime.MaxValue + offset < time)
170 return DateTime.SpecifyKind (DateTime.MaxValue, DateTimeKind.Utc);
171 } else if (offset.Ticks > 0) {
172 if (DateTime.MinValue + offset > time)
173 return DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);
176 return DateTime.SpecifyKind (new DateTime (time.Ticks - offset.Ticks), DateTimeKind.Utc);
180 // This routine returns the TimeDiff that would have to be
181 // added to "time" to turn it into a local time. This would
182 // be equivalent to call ToLocalTime.
184 // There is one important consideration:
186 // This information is only valid during the minute it
189 // This only works with a real time, not one of the boundary
190 // cases like DateTime.MaxValue, so validation must be done
193 // This is intended to be used by DateTime.Now
195 // We use a minute, just to be conservative and cope with
196 // any potential time zones that might be defined in the future
197 // that might not nicely fit in hour or half-hour steps.
199 internal TimeSpan GetLocalTimeDiff (DateTime time)
201 return GetLocalTimeDiff (time, GetUtcOffset (time));
205 // This routine is intended to be called by GetLocalTimeDiff(DatetTime)
206 // or by ToLocalTime after validation has been performed
208 // time is the time to map, utc_offset is the utc_offset that
209 // has been computed for calling GetUtcOffset on time.
211 // When called by GetLocalTime, utc_offset is assumed to come
212 // from a time constructed by new DateTime (DateTime.GetNow ()), that
215 // When called by ToLocalTime ranges are checked before this is
218 internal TimeSpan GetLocalTimeDiff (DateTime time, TimeSpan utc_offset)
220 DaylightTime dlt = GetDaylightChanges (time.Year);
222 if (dlt.Delta.Ticks == 0)
225 DateTime local = time.Add (utc_offset);
226 if (local < dlt.End && dlt.End.Subtract (dlt.Delta) <= local)
229 if (local >= dlt.Start && dlt.Start.Add (dlt.Delta) > local)
230 return utc_offset - dlt.Delta;
232 return GetUtcOffset (local);
237 internal class CurrentSystemTimeZone : TimeZone, IDeserializationCallback {
240 private string m_standardName;
241 private string m_daylightName;
243 // A yearwise cache of DaylightTime.
244 private Hashtable m_CachedDaylightChanges = new Hashtable (1);
246 // the offset when daylightsaving is not on (in ticks)
247 private long m_ticksOffset;
249 // the offset when daylightsaving is not on.
251 private TimeSpan utcOffsetWithOutDLS;
253 // the offset when daylightsaving is on.
255 private TimeSpan utcOffsetWithDLS;
257 internal enum TimeZoneData
259 DaylightSavingStartIdx,
260 DaylightSavingEndIdx,
262 AdditionalDaylightOffsetIdx
265 internal enum TimeZoneNames
271 // Internal method to get timezone data.
272 // data[0]: start of daylight saving time (in DateTime ticks).
273 // data[1]: end of daylight saving time (in DateTime ticks).
274 // data[2]: utcoffset (in TimeSpan ticks).
275 // data[3]: additional offset when daylight saving (in TimeSpan ticks).
276 // name[0]: name of this timezone when not daylight saving.
277 // name[1]: name of this timezone when daylight saving.
278 [MethodImplAttribute(MethodImplOptions.InternalCall)]
279 private static extern bool GetTimeZoneData (int year, out Int64[] data, out string[] names);
282 internal CurrentSystemTimeZone ()
287 // Initialized by the constructor
289 static int this_year;
290 static DaylightTime this_year_dlt;
293 // The "lnow" parameter must be the current time, I could have moved
294 // the code here, but I do not want to interfere with serialization
295 // which is why I kept the other constructor around
297 internal CurrentSystemTimeZone (long lnow)
302 DateTime now = new DateTime (lnow);
303 if (!GetTimeZoneData (now.Year, out data, out names))
304 throw new NotSupportedException (Locale.GetText ("Can't get timezone name."));
306 m_standardName = Locale.GetText (names[(int)TimeZoneNames.StandardNameIdx]);
307 m_daylightName = Locale.GetText (names[(int)TimeZoneNames.DaylightNameIdx]);
309 m_ticksOffset = data[(int)TimeZoneData.UtcOffsetIdx];
311 DaylightTime dlt = GetDaylightTimeFromData (data);
312 m_CachedDaylightChanges.Add (now.Year, dlt);
313 OnDeserialization (dlt);
317 public override string DaylightName {
318 get { return m_daylightName; }
321 public override string StandardName {
322 get { return m_standardName; }
326 public override DaylightTime GetDaylightChanges (int year)
328 if (year < 1 || year > 9999)
329 throw new ArgumentOutOfRangeException ("year", year +
330 Locale.GetText (" is not in a range between 1 and 9999."));
333 // First we try the case for this year, very common, and is used
334 // by DateTime.Now (a popular call) indirectly.
336 if (year == this_year)
337 return this_year_dlt;
339 lock (m_CachedDaylightChanges) {
340 DaylightTime dlt = (DaylightTime) m_CachedDaylightChanges [year];
345 if (!GetTimeZoneData (year, out data, out names))
346 throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + year));
348 dlt = GetDaylightTimeFromData (data);
349 m_CachedDaylightChanges.Add (year, dlt);
355 public override TimeSpan GetUtcOffset (DateTime time)
357 if (time.Kind == DateTimeKind.Utc)
358 return TimeSpan.Zero;
360 if (IsDaylightSavingTime (time))
361 return utcOffsetWithDLS;
363 return utcOffsetWithOutDLS;
366 void IDeserializationCallback.OnDeserialization (object sender)
368 OnDeserialization (null);
371 private void OnDeserialization (DaylightTime dlt)
377 this_year = DateTime.Now.Year;
378 if (!GetTimeZoneData (this_year, out data, out names))
379 throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + this_year));
380 dlt = GetDaylightTimeFromData (data);
382 this_year = dlt.Start.Year;
384 utcOffsetWithOutDLS = new TimeSpan (m_ticksOffset);
385 utcOffsetWithDLS = new TimeSpan (m_ticksOffset + dlt.Delta.Ticks);
389 private DaylightTime GetDaylightTimeFromData (long[] data)
391 return new DaylightTime (new DateTime (data[(int)TimeZoneData.DaylightSavingStartIdx]),
392 new DateTime (data[(int)TimeZoneData.DaylightSavingEndIdx]),
393 new TimeSpan (data[(int)TimeZoneData.AdditionalDaylightOffsetIdx]));