Merge pull request #925 from ermshiperete/novell-bug-602934
[mono.git] / mcs / class / corlib / System / TimeZone.cs
1 //
2 // System.TimeZone.cs
3 //
4 // Authors:
5 //   Duncan Mak (duncan@ximian.com)
6 //   Ajay Kumar Dwivedi (adwiv@yahoo.com)
7 //   Martin Baulig (martin@gnome.org)
8 //
9 // (C) Ximian, Inc.
10 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
11 // Copyright 2011 Xamarin Inc.
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32 //
33 // TODO:
34 //
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
39 //    of the object.
40 //
41 //    Rewrite ToUniversalTime to use a similar setup to that
42 //
43 using System.Collections.Generic;
44 using System.Globalization;
45 using System.Runtime.CompilerServices;
46 using System.Runtime.Serialization;
47 using System.Runtime.InteropServices;
48
49 namespace System
50 {
51         [Serializable]
52         [ComVisible (true)]
53         public abstract class TimeZone
54         {
55                 // Fields
56                 static TimeZone currentTimeZone;
57
58                 [NonSerialized]
59                 static object tz_lock = new object ();
60                 [NonSerialized]
61                 static long timezone_check;
62
63                 // Constructor
64                 protected TimeZone ()
65                 {
66                 }
67
68                 // Properties
69                 public static TimeZone CurrentTimeZone {
70                         get {
71                                 long now = DateTime.GetNow ();
72                                 TimeZone tz = currentTimeZone;
73                                 
74                                 lock (tz_lock) {
75                                         if (tz == null || Math.Abs (now - timezone_check) > TimeSpan.TicksPerMinute) {
76                                                 tz = new CurrentSystemTimeZone (now);
77                                                 timezone_check = now;
78
79                                                 currentTimeZone = tz;
80                                         }
81                                 }
82                                 
83                                 return tz;
84                         }
85                 }
86
87                 public abstract string DaylightName {
88                         get;
89                 }
90
91                 public abstract string StandardName {
92                         get;
93                 }
94
95                 // Methods
96                 public abstract DaylightTime GetDaylightChanges (int year);
97
98                 public abstract TimeSpan GetUtcOffset (DateTime time);
99
100                 public virtual bool IsDaylightSavingTime (DateTime time)
101                 {
102                         return IsDaylightSavingTime (time, GetDaylightChanges (time.Year));
103                 }
104
105                 public static bool IsDaylightSavingTime (DateTime time, DaylightTime daylightTimes)
106                 {
107                         if (daylightTimes == null)
108                                 throw new ArgumentNullException ("daylightTimes");
109
110                         // If Start == End, then DST is off
111                         if (daylightTimes.Start.Ticks == daylightTimes.End.Ticks)
112                                 return false;
113
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
118
119                         }
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 
124                         }
125
126                         return false;
127                 }
128
129                 public virtual DateTime ToLocalTime (DateTime time)
130                 {
131                         if (time.Kind == DateTimeKind.Local)
132                                 return time;
133
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);
141                         }
142
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);
147
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
152
153                         // PST should work fine here.
154                         if (local < dlt.End && dlt.End.Subtract (dlt.Delta) <= local)
155                                 return DateTime.SpecifyKind (local, DateTimeKind.Local);
156
157                         TimeSpan localOffset = GetUtcOffset (local);
158                         return DateTime.SpecifyKind (time.Add (localOffset), DateTimeKind.Local);
159                 }
160
161                 public virtual DateTime ToUniversalTime (DateTime time)
162                 {
163                         if (time.Kind == DateTimeKind.Utc)
164                                 return time;
165
166                         TimeSpan offset = GetUtcOffset (time);
167
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);
174                         }
175
176                         return DateTime.SpecifyKind (new DateTime (time.Ticks - offset.Ticks), DateTimeKind.Utc);
177                 }
178
179                 internal static void ClearCachedData ()
180                 {
181                         currentTimeZone = null;
182                 }
183
184                 //
185                 // This routine returns the TimeDiff that would have to be
186                 // added to "time" to turn it into a local time.   This would
187                 // be equivalent to call ToLocalTime.
188                 //
189                 // There is one important consideration:
190                 //
191                 //    This information is only valid during the minute it
192                 //    was called.
193                 //
194                 //    This only works with a real time, not one of the boundary
195                 //    cases like DateTime.MaxValue, so validation must be done
196                 //    before.
197                 // 
198                 //    This is intended to be used by DateTime.Now
199                 //
200                 // We use a minute, just to be conservative and cope with
201                 // any potential time zones that might be defined in the future
202                 // that might not nicely fit in hour or half-hour steps. 
203                 //    
204                 internal TimeSpan GetLocalTimeDiff (DateTime time)
205                 {
206                         return GetLocalTimeDiff (time, GetUtcOffset (time));
207                 }
208
209                 //
210                 // This routine is intended to be called by GetLocalTimeDiff(DatetTime)
211                 // or by ToLocalTime after validation has been performed
212                 //
213                 // time is the time to map, utc_offset is the utc_offset that
214                 // has been computed for calling GetUtcOffset on time.
215                 //
216                 // When called by GetLocalTime, utc_offset is assumed to come
217                 // from a time constructed by new DateTime (DateTime.GetNow ()), that
218                 // is a valid time.
219                 //
220                 // When called by ToLocalTime ranges are checked before this is
221                 // called.
222                 //
223                 internal TimeSpan GetLocalTimeDiff (DateTime time, TimeSpan utc_offset)
224                 {
225                         DaylightTime dlt = GetDaylightChanges (time.Year);
226
227                         if (dlt.Delta.Ticks == 0)
228                                 return utc_offset;
229
230                         DateTime local = time.Add (utc_offset);
231                         if (local < dlt.End && dlt.End.Subtract (dlt.Delta) <= local)
232                                 return utc_offset;
233
234                         if (local >= dlt.Start && dlt.Start.Add (dlt.Delta) > local)
235                                 return utc_offset - dlt.Delta;
236
237                         return GetUtcOffset (local);
238                 }
239         }
240
241         [Serializable]
242         internal class CurrentSystemTimeZone : TimeZone, IDeserializationCallback {
243
244                 // Fields
245                 private string m_standardName;
246                 private string m_daylightName;
247
248                 // A yearwise cache of DaylightTime.
249                 private Dictionary<int, DaylightTime> m_CachedDaylightChanges = new Dictionary<int, DaylightTime> (1);
250
251                 // the offset when daylightsaving is not on (in ticks)
252                 private long m_ticksOffset;
253
254                 // the offset when daylightsaving is not on.
255                 [NonSerialized]
256                 private TimeSpan utcOffsetWithOutDLS;
257   
258                 // the offset when daylightsaving is on.
259                 [NonSerialized]
260                 private TimeSpan utcOffsetWithDLS;
261
262                 internal enum TimeZoneData
263                 {
264                         DaylightSavingStartIdx,
265                         DaylightSavingEndIdx,
266                         UtcOffsetIdx,
267                         AdditionalDaylightOffsetIdx
268                 };
269
270                 internal enum TimeZoneNames
271                 {
272                         StandardNameIdx,
273                         DaylightNameIdx
274                 };
275
276                 // Internal method to get timezone data.
277                 //    data[0]:  start of daylight saving time (in DateTime ticks).
278                 //    data[1]:  end of daylight saving time (in DateTime ticks).
279                 //    data[2]:  utcoffset (in TimeSpan ticks).
280                 //    data[3]:  additional offset when daylight saving (in TimeSpan ticks).
281                 //    name[0]:  name of this timezone when not daylight saving.
282                 //    name[1]:  name of this timezone when daylight saving.
283                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
284                 private static extern bool GetTimeZoneData (int year, out Int64[] data, out string[] names);
285
286                 // Constructor
287                 internal CurrentSystemTimeZone ()
288                 {
289                 }
290
291                 //
292                 // Initialized by the constructor
293                 //
294                 static int this_year;
295                 static DaylightTime this_year_dlt;
296                 
297                 //
298                 // The "lnow" parameter must be the current time, I could have moved
299                 // the code here, but I do not want to interfere with serialization
300                 // which is why I kept the other constructor around
301                 //
302                 internal CurrentSystemTimeZone (long lnow)
303                 {
304                         Int64[] data;
305                         string[] names;
306
307                         DateTime now = new DateTime (lnow);
308                         if (!GetTimeZoneData (now.Year, out data, out names))
309                                 throw new NotSupportedException (Locale.GetText ("Can't get timezone name."));
310
311                         m_standardName = Locale.GetText (names[(int)TimeZoneNames.StandardNameIdx]);
312                         m_daylightName = Locale.GetText (names[(int)TimeZoneNames.DaylightNameIdx]);
313
314                         m_ticksOffset = data[(int)TimeZoneData.UtcOffsetIdx];
315
316                         DaylightTime dlt = GetDaylightTimeFromData (data);
317                         m_CachedDaylightChanges.Add (now.Year, dlt);
318                         OnDeserialization (dlt);
319                 }
320
321                 // Properties
322                 public override string DaylightName {
323                         get { return m_daylightName; }
324                 }
325
326                 public override string StandardName {
327                         get { return m_standardName; }
328                 }
329
330                 // Methods
331                 public override DaylightTime GetDaylightChanges (int year)
332                 {
333                         if (year < 1 || year > 9999)
334                                 throw new ArgumentOutOfRangeException ("year", year +
335                                         Locale.GetText (" is not in a range between 1 and 9999."));
336
337                         //
338                         // First we try the case for this year, very common, and is used
339                         // by DateTime.Now (a popular call) indirectly.
340                         //
341                         if (year == this_year)
342                                 return this_year_dlt;
343                         
344                         lock (m_CachedDaylightChanges) {
345                                 DaylightTime dlt;
346                                 if (!m_CachedDaylightChanges.TryGetValue (year, out dlt)) {
347                                         Int64[] data;
348                                         string[] names;
349
350                                         if (!GetTimeZoneData (year, out data, out names))
351                                                 throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + year));
352
353                                         dlt = GetDaylightTimeFromData (data);
354                                         m_CachedDaylightChanges.Add (year, dlt);
355                                 }
356                                 return dlt;
357                         }
358                 }
359
360                 public override TimeSpan GetUtcOffset (DateTime time)
361                 {
362                         if (time.Kind == DateTimeKind.Utc)
363                                 return TimeSpan.Zero;
364
365                         if (IsDaylightSavingTime (time) && !IsAmbiguousTime (time))
366                                 return utcOffsetWithDLS;
367
368                         return utcOffsetWithOutDLS;
369                 }
370
371                 private bool IsAmbiguousTime (DateTime time)
372                 {
373                         if (time.Kind == DateTimeKind.Utc)
374                                 return false;
375
376                         DaylightTime changes = GetDaylightChanges (time.Year);
377
378                         return time < changes.End && time >= changes.End - changes.Delta;
379                 }
380
381                 void IDeserializationCallback.OnDeserialization (object sender)
382                 {
383                         OnDeserialization (null);
384                 }
385
386                 private void OnDeserialization (DaylightTime dlt)
387                 {
388                         if (dlt == null) {
389                                 Int64[] data;
390                                 string[] names;
391
392                                 this_year = DateTime.Now.Year;
393                                 if (!GetTimeZoneData (this_year, out data, out names))
394                                         throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + this_year));
395                                 dlt = GetDaylightTimeFromData (data);
396                         } else
397                                 this_year = dlt.Start.Year;
398                         
399                         utcOffsetWithOutDLS = new TimeSpan (m_ticksOffset);
400                         utcOffsetWithDLS = new TimeSpan (m_ticksOffset + dlt.Delta.Ticks);
401                         this_year_dlt = dlt;
402                 }
403
404                 private DaylightTime GetDaylightTimeFromData (long[] data)
405                 {
406                         return new DaylightTime (new DateTime (data[(int)TimeZoneData.DaylightSavingStartIdx]),
407                                 new DateTime (data[(int)TimeZoneData.DaylightSavingEndIdx]),
408                                 new TimeSpan (data[(int)TimeZoneData.AdditionalDaylightOffsetIdx]));
409                 }
410
411         }
412 }