Merge pull request #347 from JamesB7/master
[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;
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;
73                                 
74                                 lock (tz_lock) {
75                                         if (currentTimeZone == null || (now - timezone_check) > TimeSpan.TicksPerMinute) {
76                                                 currentTimeZone = new CurrentSystemTimeZone (now);
77                                                 timezone_check = now;
78                                         }
79                                         
80                                         tz = currentTimeZone;
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                 //
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.
183                 //
184                 // There is one important consideration:
185                 //
186                 //    This information is only valid during the minute it
187                 //    was called.
188                 //
189                 //    This only works with a real time, not one of the boundary
190                 //    cases like DateTime.MaxValue, so validation must be done
191                 //    before.
192                 // 
193                 //    This is intended to be used by DateTime.Now
194                 //
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. 
198                 //    
199                 internal TimeSpan GetLocalTimeDiff (DateTime time)
200                 {
201                         return GetLocalTimeDiff (time, GetUtcOffset (time));
202                 }
203
204                 //
205                 // This routine is intended to be called by GetLocalTimeDiff(DatetTime)
206                 // or by ToLocalTime after validation has been performed
207                 //
208                 // time is the time to map, utc_offset is the utc_offset that
209                 // has been computed for calling GetUtcOffset on time.
210                 //
211                 // When called by GetLocalTime, utc_offset is assumed to come
212                 // from a time constructed by new DateTime (DateTime.GetNow ()), that
213                 // is a valid time.
214                 //
215                 // When called by ToLocalTime ranges are checked before this is
216                 // called.
217                 //
218                 internal TimeSpan GetLocalTimeDiff (DateTime time, TimeSpan utc_offset)
219                 {
220                         DaylightTime dlt = GetDaylightChanges (time.Year);
221
222                         if (dlt.Delta.Ticks == 0)
223                                 return utc_offset;
224
225                         DateTime local = time.Add (utc_offset);
226                         if (local < dlt.End && dlt.End.Subtract (dlt.Delta) <= local)
227                                 return utc_offset;
228
229                         if (local >= dlt.Start && dlt.Start.Add (dlt.Delta) > local)
230                                 return utc_offset - dlt.Delta;
231
232                         return GetUtcOffset (local);
233                 }
234         }
235
236         [Serializable]
237         internal class CurrentSystemTimeZone : TimeZone, IDeserializationCallback {
238
239                 // Fields
240                 private string m_standardName;
241                 private string m_daylightName;
242
243                 // A yearwise cache of DaylightTime.
244                 private Hashtable m_CachedDaylightChanges = new Hashtable (1);
245
246                 // the offset when daylightsaving is not on (in ticks)
247                 private long m_ticksOffset;
248
249                 // the offset when daylightsaving is not on.
250                 [NonSerialized]
251                 private TimeSpan utcOffsetWithOutDLS;
252   
253                 // the offset when daylightsaving is on.
254                 [NonSerialized]
255                 private TimeSpan utcOffsetWithDLS;
256
257                 internal enum TimeZoneData
258                 {
259                         DaylightSavingStartIdx,
260                         DaylightSavingEndIdx,
261                         UtcOffsetIdx,
262                         AdditionalDaylightOffsetIdx
263                 };
264
265                 internal enum TimeZoneNames
266                 {
267                         StandardNameIdx,
268                         DaylightNameIdx
269                 };
270
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);
280
281                 // Constructor
282                 internal CurrentSystemTimeZone ()
283                 {
284                 }
285
286                 //
287                 // Initialized by the constructor
288                 //
289                 static int this_year;
290                 static DaylightTime this_year_dlt;
291                 
292                 //
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
296                 //
297                 internal CurrentSystemTimeZone (long lnow)
298                 {
299                         Int64[] data;
300                         string[] names;
301
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."));
305
306                         m_standardName = Locale.GetText (names[(int)TimeZoneNames.StandardNameIdx]);
307                         m_daylightName = Locale.GetText (names[(int)TimeZoneNames.DaylightNameIdx]);
308
309                         m_ticksOffset = data[(int)TimeZoneData.UtcOffsetIdx];
310
311                         DaylightTime dlt = GetDaylightTimeFromData (data);
312                         m_CachedDaylightChanges.Add (now.Year, dlt);
313                         OnDeserialization (dlt);
314                 }
315
316                 // Properties
317                 public override string DaylightName {
318                         get { return m_daylightName; }
319                 }
320
321                 public override string StandardName {
322                         get { return m_standardName; }
323                 }
324
325                 // Methods
326                 public override DaylightTime GetDaylightChanges (int year)
327                 {
328                         if (year < 1 || year > 9999)
329                                 throw new ArgumentOutOfRangeException ("year", year +
330                                         Locale.GetText (" is not in a range between 1 and 9999."));
331
332                         //
333                         // First we try the case for this year, very common, and is used
334                         // by DateTime.Now (a popular call) indirectly.
335                         //
336                         if (year == this_year)
337                                 return this_year_dlt;
338                         
339                         lock (m_CachedDaylightChanges) {
340                                 DaylightTime dlt = (DaylightTime) m_CachedDaylightChanges [year];
341                                 if (dlt == null) {
342                                         Int64[] data;
343                                         string[] names;
344
345                                         if (!GetTimeZoneData (year, out data, out names))
346                                                 throw new ArgumentException (Locale.GetText ("Can't get timezone data for " + year));
347
348                                         dlt = GetDaylightTimeFromData (data);
349                                         m_CachedDaylightChanges.Add (year, dlt);
350                                 }
351                                 return dlt;
352                         }
353                 }
354
355                 public override TimeSpan GetUtcOffset (DateTime time)
356                 {
357                         if (time.Kind == DateTimeKind.Utc)
358                                 return TimeSpan.Zero;
359
360                         if (IsDaylightSavingTime (time))
361                                 return utcOffsetWithDLS;
362
363                         return utcOffsetWithOutDLS;
364                 }
365
366                 void IDeserializationCallback.OnDeserialization (object sender)
367                 {
368                         OnDeserialization (null);
369                 }
370
371                 private void OnDeserialization (DaylightTime dlt)
372                 {
373                         if (dlt == null) {
374                                 Int64[] data;
375                                 string[] names;
376
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);
381                         } else
382                                 this_year = dlt.Start.Year;
383                         
384                         utcOffsetWithOutDLS = new TimeSpan (m_ticksOffset);
385                         utcOffsetWithDLS = new TimeSpan (m_ticksOffset + dlt.Delta.Ticks);
386                         this_year_dlt = dlt;
387                 }
388
389                 private DaylightTime GetDaylightTimeFromData (long[] data)
390                 {
391                         return new DaylightTime (new DateTime (data[(int)TimeZoneData.DaylightSavingStartIdx]),
392                                 new DateTime (data[(int)TimeZoneData.DaylightSavingEndIdx]),
393                                 new TimeSpan (data[(int)TimeZoneData.AdditionalDaylightOffsetIdx]));
394                 }
395
396         }
397 }