merged Sys.Web.Services 2.0 support in my branch:
[mono.git] / mcs / class / corlib / System / DateTime.cs
1 //
2 // System.DateTime.cs
3 //
4 // author:
5 //   Marcel Narings (marcel@narings.nl)
6 //   Martin Baulig (martin@gnome.org)
7 //   Atsushi Enomoto (atsushi@ximian.com)
8 //
9 //   (C) 2001 Marcel Narings
10 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Globalization;
34 using System.Runtime.CompilerServices;
35 using System.Runtime.InteropServices;
36 using System.Text;
37
38 namespace System
39 {
40         /// <summary>
41         /// The DateTime structure represents dates and time ranging from
42         /// 1-1-0001 12:00:00 AM to 31-12-9999 23:59:00 Common Era.
43         /// </summary>
44         /// 
45         [Serializable]
46         [StructLayout (LayoutKind.Auto)]
47         public struct DateTime : IFormattable, IConvertible, IComparable
48 #if NET_2_0
49                 , IComparable<DateTime>, IEquatable <DateTime>
50 #endif
51         {
52                 private TimeSpan ticks;
53
54 #if NET_2_0
55                 DateTimeKind kind;
56 #endif
57
58                 private const int dp400 = 146097;
59                 private const int dp100 = 36524;
60                 private const int dp4 = 1461;
61
62                 // w32 file time starts counting from 1/1/1601 00:00 GMT
63                 // which is the constant ticks from the .NET epoch
64                 private const long w32file_epoch = 504911232000000000L;
65
66                 //private const long MAX_VALUE_TICKS = 3155378975400000000L;
67                 // -- Microsoft .NET has this value.
68                 private const long MAX_VALUE_TICKS = 3155378975999999999L;
69
70                 //
71                 // The UnixEpoch, it begins on Jan 1, 1970 at 0:0:0, expressed
72                 // in Ticks
73                 //
74                 internal const long UnixEpoch = 621355968000000000L;
75
76                 // for OLE Automation dates
77                 private const long ticks18991230 = 599264352000000000L;
78                 private const double OAMinValue = -657435.0d;
79                 private const double OAMaxValue = 2958466.0d;
80
81                 public static readonly DateTime MaxValue = new DateTime (false, new TimeSpan (MAX_VALUE_TICKS));
82                 public static readonly DateTime MinValue = new DateTime (false, new TimeSpan (0));
83
84                 private static readonly string[] commonFormats = {
85                         // For compatibility with MS's CLR, this format (which
86                         // doesn't have a one-letter equivalent) is parsed
87                         // too. It's important because it's used in XML
88                         // serialization.
89
90                         // Note that those format should be tried only for
91                         // invalid patterns; 
92
93                         // FIXME: SOME OF those patterns looks tried against 
94                         // the current culture, since some patterns fail in 
95                         // some culture.
96
97                         "yyyy-MM-dd",
98                         "yyyy-MM-ddTHH:mm:sszzz",
99                         "yyyy-MM-ddTHH:mm:ss.fffffff",
100                         "yyyy-MM-ddTHH:mm:ss.fffffffzzz",
101                         // bug #78618
102                         "yyyy-M-d H:m:s.fffffff",
103                         // UTC / allow any separator
104                         "yyyy/MM/ddTHH:mm:ssZ",
105                         "yyyy/M/dZ",
106                         // bug #58938
107                         "yyyy/M/d HH:mm:ss",
108                         // bug #47720
109                         "yyyy/MM/dd HH:mm:ss 'GMT'",
110                         // bug #53023
111                         "MM/dd/yyyy",
112                         // Close to RFC1123, but without 'GMT'
113                         "ddd, d MMM yyyy HH:mm:ss",
114                         // use UTC ('Z'; not literal "'Z'")
115                         // FIXME: 1078(af-ZA) and 1079(ka-GE) reject it
116                         "yyyy/MM/dd HH':'mm':'ssZ", 
117
118                         // bug #60912
119                         "M/d/yyyy HH':'mm':'ss tt",
120                         "H':'mm':'ss tt",
121                         // another funky COM dependent one
122                         "dd-MMM-yy",
123
124                         // DayOfTheWeek, dd full_month_name yyyy
125                         // FIXME: 1054(th-TH) rejects them
126                         "dddd, dd MMMM yyyy",
127                         "dddd, dd MMMM yyyy HH:mm",
128                         "dddd, dd MMMM yyyy HH:mm:ss",
129
130                         "yyyy MMMM",
131                         // DayOfTheWeek, dd yyyy. This works for every locales.
132                         "MMMM dd, yyyy",
133 #if NET_1_1
134                         // X509Certificate pattern is accepted by Parse() *in every culture*
135                         "yyyyMMddHHmmssZ",
136 #endif
137                         // In Parse() the 'r' equivalent pattern is first parsed as universal time
138                         "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
139
140                         // Additionally there seems language-specific format
141                         // patterns that however works in all language
142                         // environment.
143                         // For example, the pattern below is for Japanese.
144                         "yyyy'\u5E74'MM'\u6708'dd'\u65E5' HH'\u6642'mm'\u5206'ss'\u79D2'",
145
146 /*
147                         // Full date and time
148                         "F", "G", "r", "s", "u", "U",
149                         // Full date and time, but no seconds
150                         "f", "g",
151                         // Only date
152                         "d", "D",
153                         // Only time
154                         "T", "t",
155                         // Only date, but no year
156                         "m",
157                         // Only date, but no day
158                         "y" 
159 */
160                 };
161
162                 private enum Which 
163                 {
164                         Day,
165                         DayYear,
166                         Month,
167                         Year
168                 };
169         
170                 private static readonly int[] daysmonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };        
171                 private static readonly int[] daysmonthleap = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };    
172
173                 private static int AbsoluteDays (int year, int month, int day)
174                 {
175                         int[] days;
176                         int temp = 0, m=1 ;
177                 
178                         days = (IsLeapYear(year) ? daysmonthleap  : daysmonth);
179                         
180                         while (m < month)
181                                 temp += days[m++];
182                         return ((day-1) + temp + (365* (year-1)) + ((year-1)/4) - ((year-1)/100) + ((year-1)/400));
183                 }
184
185                 private int FromTicks(Which what)
186                 {
187                         int num400, num100, num4, numyears; 
188                         int M =1;
189
190                         int[] days = daysmonth;
191                         int totaldays = this.ticks.Days;
192
193                         num400 = (totaldays / dp400);
194                         totaldays -=  num400 * dp400;
195                 
196                         num100 = (totaldays / dp100);
197                         if (num100 == 4)   // leap
198                                 num100 = 3;
199                         totaldays -= (num100 * dp100);
200
201                         num4 = totaldays / dp4;
202                         totaldays -= (num4 * dp4);
203
204                         numyears = totaldays / 365 ;
205
206                         if (numyears == 4)  //leap
207                                 numyears =3 ;
208                         if (what == Which.Year )
209                                 return num400*400 + num100*100 + num4*4 + numyears + 1;
210
211                         totaldays -= (numyears * 365) ;
212                         if (what == Which.DayYear )
213                                 return totaldays + 1;
214                         
215                         if  ((numyears==3) && ((num100 == 3) || !(num4 == 24)) ) //31 dec leapyear
216                                 days = daysmonthleap;
217                                 
218                         while (totaldays >= days[M])
219                                 totaldays -= days[M++];
220
221                         if (what == Which.Month )
222                                 return M;
223
224                         return totaldays +1; 
225                 }
226
227
228                 // Constructors
229                 
230                 /// <summary>
231                 /// Constructs a DateTime for specified ticks
232                 /// </summary>
233                 /// 
234                 public DateTime (long ticks)
235                 {
236                         this.ticks = new TimeSpan (ticks);
237                         if (ticks < MinValue.Ticks || ticks > MaxValue.Ticks) {
238                                 string msg = Locale.GetText ("Value {0} is outside the valid range [{1},{2}].", 
239                                         ticks, MinValue.Ticks, MaxValue.Ticks);
240                                 throw new ArgumentOutOfRangeException ("ticks", msg);
241                         }
242 #if NET_2_0
243                         kind = DateTimeKind.Unspecified;
244 #endif
245                 }
246
247                 public DateTime (int year, int month, int day)
248                         : this (year, month, day,0,0,0,0) {}
249
250                 public DateTime (int year, int month, int day, int hour, int minute, int second)
251                         : this (year, month, day, hour, minute, second, 0)      {}
252
253                 public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond)
254                         {
255                         if ( year < 1 || year > 9999 || 
256                                 month < 1 || month >12  ||
257                                 day < 1 || day > DaysInMonth(year, month) ||
258                                 hour < 0 || hour > 23 ||
259                                 minute < 0 || minute > 59 ||
260                                 second < 0 || second > 59 ||
261                                 millisecond < 0 || millisecond > 999)
262                                 throw new ArgumentOutOfRangeException ("Parameters describe an " +
263                                                                         "unrepresentable DateTime.");
264
265                         ticks = new TimeSpan (AbsoluteDays(year,month,day), hour, minute, second, millisecond);
266
267 #if NET_2_0
268                         kind = DateTimeKind.Unspecified;
269 #endif
270                 }
271
272                 [MonoTODO ("The Calendar is not taken into consideration")]
273                 public DateTime (int year, int month, int day, Calendar calendar)
274                         : this (year, month, day, 0, 0, 0, 0, calendar)
275                 {
276                 }
277                 
278                 [MonoTODO ("The Calendar is not taken into consideration")]
279                 public DateTime (int year, int month, int day, int hour, int minute, int second, Calendar calendar)
280                         : this (year, month, day, hour, minute, second, 0, calendar)
281                 {
282                 }
283
284                 [MonoTODO ("The Calendar is not taken into consideration")]
285                 public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar)
286                         : this (year, month, day, hour, minute, second, millisecond) 
287                 {
288                         if (calendar == null)
289                                 throw new ArgumentNullException ("calendar");
290                 }
291
292                 internal DateTime (bool check, TimeSpan value)
293                 {
294                         if (check && (value.Ticks < MinValue.Ticks || value.Ticks > MaxValue.Ticks))
295                             throw new ArgumentOutOfRangeException ();
296
297                         ticks = value;
298
299 #if NET_2_0
300                         kind = DateTimeKind.Unspecified;
301 #endif
302                 }
303
304 #if NET_2_0
305                 public DateTime (long ticks, DateTimeKind kind) : this (ticks)
306                 {
307                         CheckDateTimeKind (kind);
308                         this.kind = kind;
309                 }
310
311                 public DateTime (int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
312                         : this (year, month, day, hour, minute, second)
313                 {
314                         CheckDateTimeKind (kind);
315                         this.kind = kind;
316                 }
317
318                 public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
319                         : this (year, month, day, hour, minute, second, millisecond)
320                 {
321                         CheckDateTimeKind (kind);
322                         this.kind = kind;
323                 }
324
325                 public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind)
326                         : this (year, month, day, hour, minute, second, millisecond, calendar)
327                 {
328                         CheckDateTimeKind (kind);
329                         this.kind = kind;
330                 }                       
331 #endif
332
333                 /* Properties  */
334
335                 public DateTime Date 
336                 {
337                         get     
338                         { 
339                                 return new DateTime (Year, Month, Day);
340                         }
341                 }
342         
343                 public int Month 
344                 {
345                         get     
346                         { 
347                                 return FromTicks(Which.Month); 
348                         }
349                 }
350
351                
352                 public int Day
353                 {
354                         get 
355                         { 
356                                 return FromTicks(Which.Day); 
357                         }
358                 }
359
360                 public DayOfWeek DayOfWeek 
361                 {
362                         get 
363                         { 
364                                 return ( (DayOfWeek) ((ticks.Days+1) % 7) ); 
365                         }
366                 }
367
368                 public int DayOfYear 
369                 {
370                         get 
371                         { 
372                                 return FromTicks(Which.DayYear); 
373                         }
374                 }
375
376                 public TimeSpan TimeOfDay 
377                 {
378                         get     
379                         { 
380                                 return new TimeSpan(ticks.Ticks % TimeSpan.TicksPerDay );
381                         }
382                         
383                 }
384
385                 public int Hour 
386                 {
387                         get 
388                         { 
389                                 return ticks.Hours;
390                         }
391                 }
392
393                 public int Minute 
394                 {
395                         get 
396                         { 
397                                 return ticks.Minutes;
398                         }
399                 }
400
401                 public int Second 
402                 {
403                         get     
404                         { 
405                                 return ticks.Seconds;
406                         }
407                 }
408
409                 public int Millisecond 
410                 {
411                         get 
412                         { 
413                                 return ticks.Milliseconds;
414                         }
415                 }
416                 
417                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
418                 internal static extern long GetNow ();
419
420                 //
421                 // To reduce the time consumed by DateTime.Now, we keep
422                 // the difference to map the system time into a local
423                 // time into `to_local_time_span', we record the timestamp
424                 // for this in `last_now'
425                 //
426                 static object to_local_time_span_object;
427                 static long last_now;
428                 
429                 public static DateTime Now 
430                 {
431                         get     
432                         {
433                                 long now = GetNow ();
434                                 DateTime dt = new DateTime (now);
435
436                                 if ((now - last_now) > TimeSpan.TicksPerMinute){
437                                         to_local_time_span_object = TimeZone.CurrentTimeZone.GetLocalTimeDiff (dt);
438                                         last_now = now;
439
440                                 }
441
442                                 // This is boxed, so we avoid locking.
443                                 DateTime ret = dt + (TimeSpan) to_local_time_span_object;
444 #if NET_2_0
445                                 ret.kind = DateTimeKind.Local;
446 #endif
447                                 return ret;
448                         }
449                 }
450
451                 public long Ticks
452                 { 
453                         get     
454                         { 
455                                 return ticks.Ticks;
456                         }
457                 }
458         
459                 public static DateTime Today 
460                 {
461                         get {
462                                 DateTime now = Now;
463                                 DateTime today = new DateTime (now.Year, now.Month, now.Day);
464 #if NET_2_0
465                                 today.kind = now.kind;
466 #endif
467                                 return today;
468                         }
469                 }
470
471                 public static DateTime UtcNow 
472                 {
473                         get {
474 #if NET_2_0
475                                 return new DateTime (GetNow (), DateTimeKind.Utc);
476 #else
477                                 return new DateTime (GetNow ());
478 #endif
479                         }
480                 }
481
482                 public int Year 
483                 {
484                         get 
485                         { 
486                                 return FromTicks(Which.Year); 
487                         }
488                 }
489
490 #if NET_2_0
491                 public DateTimeKind Kind {
492                         get {
493                                 return kind;
494                         }
495                 }
496 #endif
497
498                 /* methods */
499
500                 public DateTime Add (TimeSpan ts)
501                 {
502                         return AddTicks (ts.Ticks);
503                 }
504
505                 public DateTime AddDays (double days)
506                 {
507                         return AddMilliseconds (Math.Round (days * 86400000));
508                 }
509                 
510                 public DateTime AddTicks (long t)
511                 {
512                         if ((t + ticks.Ticks) > MAX_VALUE_TICKS || (t + ticks.Ticks) < 0) {
513                                 throw new ArgumentOutOfRangeException();
514                         }
515                         return new DateTime (t + ticks.Ticks);
516                 }
517
518                 public DateTime AddHours (double hours)
519                 {
520                         return AddMilliseconds (hours * 3600000);
521                 }
522
523                 public DateTime AddMilliseconds (double ms)
524                 {
525                         if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
526                                         (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
527                                 throw new ArgumentOutOfRangeException();
528                         }
529                         long msticks = (long) (ms * TimeSpan.TicksPerMillisecond);
530
531                         return AddTicks (msticks);
532                 }
533
534                 // required to match MS implementation for OADate (OLE Automation)
535                 private DateTime AddRoundedMilliseconds (double ms)
536                 {
537                         if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
538                                 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
539                                 throw new ArgumentOutOfRangeException ();
540                         }
541                         long msticks = (long) (ms += ms > 0 ? 0.5 : -0.5) * TimeSpan.TicksPerMillisecond;
542
543                         return AddTicks (msticks);
544                 }
545
546                 public DateTime AddMinutes (double minutes)
547                 {
548                         return AddMilliseconds (minutes * 60000);
549                 }
550                 
551                 public DateTime AddMonths (int months)
552                 {
553                         int day, month, year,  maxday ;
554                         DateTime temp ;
555
556                         day = this.Day;
557                         month = this.Month + (months % 12);
558                         year = this.Year + months/12 ;
559                         
560                         if (month < 1)
561                         {
562                                 month = 12 + month ;
563                                 year -- ;
564                         }
565                         else if (month>12) 
566                         {
567                                 month = month -12;
568                                 year ++;
569                         }
570                         maxday = DaysInMonth(year, month);
571                         if (day > maxday)
572                                 day = maxday;
573
574                         temp = new DateTime (year, month, day);
575                         return  temp.Add (this.TimeOfDay);
576                 }
577
578                 public DateTime AddSeconds (double seconds)
579                 {
580                         return AddMilliseconds (seconds*1000);
581                 }
582
583                 public DateTime AddYears (int years )
584                 {
585                         return AddMonths(years * 12);
586                 }
587
588                 public static int Compare (DateTime t1, DateTime t2)
589                 {
590                         if (t1.ticks < t2.ticks) 
591                                 return -1;
592                         else if (t1.ticks > t2.ticks) 
593                                 return 1;
594                         else
595                                 return 0;
596                 }
597
598                 public int CompareTo (object v)
599                 {
600                         if ( v == null)
601                                 return 1;
602
603                         if (!(v is System.DateTime))
604                                 throw new ArgumentException (Locale.GetText (
605                                         "Value is not a System.DateTime"));
606
607                         return Compare (this, (DateTime) v);
608                 }
609
610 #if NET_2_0
611                 public bool IsDaylightSavingTime ()
612                 {
613                         if (kind == DateTimeKind.Utc)
614                                 return false;
615                         return TimeZone.CurrentTimeZone.IsDaylightSavingTime (this);
616                 }
617
618                 public int CompareTo (DateTime value)
619                 {
620                         return Compare (this, value);
621                 }
622
623                 public bool Equals (DateTime value)
624                 {
625                         return value.ticks == ticks;
626                 }
627
628                 public long ToBinary ()
629                 {
630                         switch (kind) {
631                         case DateTimeKind.Utc:
632                                 return Ticks | 0x4000000000000000;
633                         case DateTimeKind.Local:
634                                 return (long) ((ulong)Ticks | 0x8000000000000000);
635                         default:
636                                 return Ticks;
637                         }
638                 }
639
640                 public static DateTime FromBinary (long dateData)
641                 {
642                         switch ((ulong)dateData >> 62) {
643                         case 1:
644                                 return new DateTime (dateData ^ 0x4000000000000000, DateTimeKind.Utc);
645                         case 0:
646                                 return new DateTime (dateData, DateTimeKind.Unspecified);
647                         default:
648                                 return new DateTime (((dateData << 2) >> 2), DateTimeKind.Local);
649                         }
650                 }
651
652                 public static DateTime SpecifyKind (DateTime value, DateTimeKind kind)
653                 {
654                         return new DateTime (value.Ticks, kind);
655                 }
656 #endif
657
658                 public static int DaysInMonth (int year, int month)
659                 {
660                         int[] days ;
661
662                         if (month < 1 || month >12)
663                                 throw new ArgumentOutOfRangeException ();
664
665                         days = (IsLeapYear(year) ? daysmonthleap  : daysmonth);
666                         return days[month];                     
667                 }
668                 
669                 public override bool Equals (object o)
670                 {
671                         if (!(o is System.DateTime))
672                                 return false;
673
674                         return ((DateTime) o).ticks == ticks;
675                 }
676
677                 public static bool Equals (DateTime t1, DateTime t2 )
678                 {
679                         return (t1.ticks == t2.ticks );
680                 }
681
682                 public static DateTime FromFileTime (long fileTime) 
683                 {
684                         if (fileTime < 0)
685                                 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
686
687                         return new DateTime (w32file_epoch + fileTime).ToLocalTime ();
688                 }
689
690 #if NET_1_1
691                 public static DateTime FromFileTimeUtc (long fileTime) 
692                 {
693                         if (fileTime < 0)
694                                 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
695
696                         return new DateTime (w32file_epoch + fileTime);
697                 }
698 #endif
699
700                 public static DateTime FromOADate (double d)
701                 {
702                         // An OLE Automation date is implemented as a floating-point number
703                         // whose value is the number of days from midnight, 30 December 1899.
704
705                         // d must be negative 657435.0 through positive 2958466.0.
706                         if ((d <= OAMinValue) || (d >= OAMaxValue))
707                                 throw new ArgumentException ("d", "[-657435,2958466]");
708
709                         DateTime dt = new DateTime (ticks18991230);
710                         if (d < 0.0d) {
711                                 Double days = Math.Ceiling (d);
712                                 // integer part is the number of days (negative)
713                                 dt = dt.AddRoundedMilliseconds (days * 86400000);
714                                 // but decimals are the number of hours (in days fractions) and positive
715                                 Double hours = (days - d);
716                                 dt = dt.AddRoundedMilliseconds (hours * 86400000);
717                         }
718                         else {
719                                 dt = dt.AddRoundedMilliseconds (d * 86400000);
720                         }
721
722                         return dt;
723                 }
724
725                 public string[] GetDateTimeFormats() 
726                 {
727                         return GetDateTimeFormats (CultureInfo.CurrentCulture);
728                 }
729
730                 public string[] GetDateTimeFormats(char format)
731                 {
732                         if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
733                                 throw new FormatException ("Invalid format character.");
734                         string[] result = new string[1];
735                         result[0] = this.ToString(format.ToString());
736                         return result;
737                 }
738                 
739                 public string[] GetDateTimeFormats(IFormatProvider provider)
740                 {
741                         DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
742 //                      return GetDateTimeFormats (info.GetAllDateTimePatterns ());
743                         ArrayList al = new ArrayList ();
744                         foreach (char c in "dDgGfFmMrRstTuUyY")
745                                 al.AddRange (GetDateTimeFormats (c, info));
746                         return al.ToArray (typeof (string)) as string [];
747                 }
748
749                 public string[] GetDateTimeFormats(char format,IFormatProvider provider )
750                 {
751                         if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
752                                 throw new FormatException ("Invalid format character.");
753
754                         // LAMESPEC: There is NO assurance that 'U' ALWAYS
755                         // euqals to 'F', but since we have to iterate all
756                         // the pattern strings, we cannot just use 
757                         // ToString("U", provider) here. I believe that the 
758                         // method's behavior cannot be formalized.
759                         bool adjustutc = false;
760                         switch (format) {
761                         case 'U':
762 //                      case 'r':
763 //                      case 'R':
764 //                      case 'u':
765                                 adjustutc = true;
766                                 break;
767                         }
768                         DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
769                         return GetDateTimeFormats (adjustutc, info.GetAllRawDateTimePatterns (format), info);
770                 }
771
772                 private string [] GetDateTimeFormats (bool adjustutc, string [] patterns, DateTimeFormatInfo dfi)
773                 {
774                         string [] results = new string [patterns.Length];
775                         DateTime val = adjustutc ? ToUniversalTime () : this;
776                         for (int i = 0; i < results.Length; i++)
777                                 results [i] = val._ToString (patterns [i], dfi);
778                         return results;
779                 }
780
781 #if NET_2_0
782                 private void CheckDateTimeKind (DateTimeKind kind) {
783                         if ((kind != DateTimeKind.Unspecified) && (kind != DateTimeKind.Utc) && (kind != DateTimeKind.Local))
784                                 throw new ArgumentException ("Invalid DateTimeKind value.", "kind");
785                 }
786 #endif
787
788                 public override int GetHashCode ()
789                 {
790                         return (int) ticks.Ticks;
791                 }
792
793                 public TypeCode GetTypeCode ()
794                 {
795                         return TypeCode.DateTime;
796                 }
797
798                 public static bool IsLeapYear (int year)
799                 {
800                         return  ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
801                 }
802
803                 public static DateTime Parse (string s)
804                 {
805                         return Parse (s, null);
806                 }
807
808                 public static DateTime Parse (string s, IFormatProvider fp)
809                 {
810                         return Parse (s, fp, DateTimeStyles.AllowWhiteSpaces);
811                 }
812
813                 public static DateTime Parse (string s, IFormatProvider fp, DateTimeStyles styles)
814                 {
815                         // This method should try only expected patterns. 
816                         // Should not try extra patterns.
817                         // Right now we also try InvariantCulture, but I
818                         // confirmed in some cases this method rejects what
819                         // InvariantCulture supports (can be checked against
820                         // "th-TH" with Gregorian Calendar). So basically it
821                         // should not be done.
822                         // I think it should be CurrentCulture to be tested,
823                         // but right now we don't support all the supported
824                         // patterns for each culture, so try InvariantCulture
825                         // as a quick remedy.
826                         if (s == null)
827                                 throw new ArgumentNullException (Locale.GetText ("s is null"));
828                         DateTime result;
829
830                         if (fp == null)
831                                 fp = CultureInfo.CurrentCulture;
832                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
833
834                         bool longYear = false;
835
836                         // Try all the patterns
837                         if (ParseExact (s, dfi.GetAllDateTimePatternsInternal (), dfi, styles, out result, false, ref longYear))
838                                 return result;
839
840                         // Try common formats.
841 //                      if (ParseExact (s, commonFormats, dfi, styles, out result, false, ref longYear))
842 //                              return result;
843
844                         // Try common formats with invariant culture
845                         if (ParseExact (s, commonFormats, DateTimeFormatInfo.InvariantInfo, styles, out result, false, ref longYear))
846                                 return result;
847
848                         if (longYear) {
849                                 throw new ArgumentOutOfRangeException ("year",
850                                         "Valid values are between 1 and 9999 inclusive");
851                         }
852
853                         throw new FormatException ("String was not recognized as a valid DateTime.");
854                 }
855
856                 public static DateTime ParseExact (string s, string format, IFormatProvider fp)
857                 {
858                         return ParseExact (s, format, fp, DateTimeStyles.None);
859                 }
860
861                 internal static int _ParseNumber (string s, int valuePos,
862                                                   int min_digits,
863                                                   int digits,
864                                                   bool leadingzero,
865                                                   bool sloppy_parsing,
866                                                   out int num_parsed)
867                 {
868                         int number = 0, i;
869
870                         if (sloppy_parsing)
871                                 leadingzero = false;
872
873                         if (!leadingzero) {
874                                 int real_digits = 0;
875                                 for (i = valuePos; i < s.Length && i < digits + valuePos; i++) {
876                                         if (!Char.IsDigit (s[i]))
877                                                 break;
878
879                                         real_digits++;
880                                 }
881
882                                 digits = real_digits;
883                         }
884                         if (digits < min_digits) {
885                                 num_parsed = -1;
886                                 return 0;
887                         }
888
889                         if (s.Length - valuePos < digits) {
890                                 num_parsed = -1;
891                                 return 0;
892                         }
893
894                         for (i = valuePos; i < digits + valuePos; i++) {
895                                 char c = s[i];
896                                 if (!Char.IsDigit (c)) {
897                                         num_parsed = -1;
898                                         return 0;
899                                 }
900
901                                 number = number * 10 + (byte) (c - '0');
902                         }
903
904                         num_parsed = digits;
905                         return number;
906                 }
907
908                 internal static int _ParseEnum (string s, int sPos, string[] values, out int num_parsed)
909                 {
910                         int i;
911
912                         // FIXME: I know this is somehow lame code. Probably
913                         // it should iterate all the enum value and return
914                         // the longest match. However right now I don't see
915                         // anything but "1" and "10" - "12" that might match
916                         // two or more values. (They are only abbrev month
917                         // names, so do reverse order search). See bug #80094.
918                         for (i = values.Length - 1; i >= 0; i--) {
919                                 if (s.Length - sPos < values[i].Length)
920                                         continue;
921                                 else if (values [i].Length == 0)
922                                         continue;
923                                 String tmp = s.Substring (sPos, values[i].Length);
924                                 if (String.Compare (tmp, values[i], true) == 0) {
925                                         num_parsed = values[i].Length;
926                                         return i;
927                                 }
928                         }
929
930                         num_parsed = -1;
931                         return -1;
932                 }
933
934                 internal static bool _ParseString (string s, int sPos, int maxlength, string value, out int num_parsed)
935                 {
936                         if (maxlength <= 0)
937                                 maxlength = value.Length;
938
939                         if (String.Compare (s, sPos, value, 0, maxlength, true, CultureInfo.InvariantCulture) == 0) {
940                                 num_parsed = maxlength;
941                                 return true;
942                         }
943
944                         num_parsed = -1;
945                         return false;
946                 }
947
948                 private static bool _DoParse (string s, string format, bool exact,
949                                                out DateTime result,
950                                                DateTimeFormatInfo dfi,
951                                                DateTimeStyles style,
952                                                ref bool longYear)
953                 {
954                         bool useutc = false, use_localtime = true;
955                         bool use_invariant = false;
956                         bool sloppy_parsing = false;
957                         int valuePos = 0;
958                         if (format.Length == 1)
959                                 format = _GetStandardPattern (format [0], dfi, out useutc, out use_invariant);
960                         else if (!exact && CultureInfo.InvariantCulture.CompareInfo.IndexOf (format, "GMT", CompareOptions.Ordinal) >= 0)
961                                 useutc = true;
962
963                         if ((style & DateTimeStyles.AllowLeadingWhite) != 0) {
964                                 format = format.TrimStart (null);
965
966                                 s = s.TrimStart (null); // it could be optimized, but will make little good.
967                         }
968
969                         if ((style & DateTimeStyles.AllowTrailingWhite) != 0) {
970                                 format = format.TrimEnd (null);
971                                 s = s.TrimEnd (null); // it could be optimized, but will make little good.
972                         }
973
974                         if (use_invariant)
975                                 dfi = DateTimeFormatInfo.InvariantInfo;
976
977                         if ((style & DateTimeStyles.AllowInnerWhite) != 0)
978                                 sloppy_parsing = true;
979
980                         string chars = format;
981                         int len = format.Length, pos = 0, num = 0;
982
983                         int day = -1, dayofweek = -1, month = -1, year = -1;
984                         int hour = -1, minute = -1, second = -1;
985                         double fractionalSeconds = -1;
986                         int ampm = -1;
987                         int tzsign = -1, tzoffset = -1, tzoffmin = -1;
988
989                         result = new DateTime (0);
990                         while (pos+num < len)
991                         {
992                                 if (s.Length == valuePos)
993                                         break;
994
995                                 if (chars[pos] == '\'') {
996                                         num = 1;
997                                         while (pos+num < len) {
998                                                 if (chars[pos+num] == '\'')
999                                                         break;
1000
1001                                                 if (valuePos == s.Length)
1002                                                         return false;
1003                                                 if (s [valuePos] != chars [pos + num])
1004                                                         return false;
1005                                                 valuePos++;
1006
1007                                                 num++;
1008                                         }
1009                                         if (pos+num > len)
1010                                                 return false;
1011
1012                                         pos += num + 1;
1013                                         num = 0;
1014                                         continue;
1015                                 } else if (chars[pos] == '"') {
1016                                         num = 1;
1017                                         while (pos+num < len) {
1018                                                 if (chars[pos+num] == '"')
1019                                                         break;
1020
1021                                                 if (valuePos == s.Length)
1022                                                         return false;
1023                                                 if (s [valuePos] != chars[pos+num])
1024                                                         return false;
1025                                                 valuePos++;
1026
1027                                                 num++;
1028                                         }
1029                                         if (pos+num > len)
1030                                                 return false;
1031
1032                                         pos += num + 1;
1033                                         num = 0;
1034                                         continue;
1035                                 } else if (chars[pos] == '\\') {
1036                                         pos += num + 1;
1037                                         num = 0;
1038                                         if (pos >= len)
1039                                                 return false;
1040
1041                                         if (s [valuePos] != chars [pos])
1042                                                 return false;
1043                                         valuePos++;
1044                                         pos++;
1045                                         continue;
1046                                 } else if (chars[pos] == '%') {
1047                                         pos++;
1048                                         continue;
1049                                 } else if (Char.IsWhiteSpace (s [valuePos]) ||
1050                                         s [valuePos] == ',' && Char.IsWhiteSpace (chars [pos])) {
1051                                         valuePos++;
1052                                         num = 0;
1053                                         if (exact && (style & DateTimeStyles.AllowInnerWhite) == 0) {
1054                                                 if (!Char.IsWhiteSpace (chars[pos]))
1055                                                         return false;
1056                                                 pos++;
1057                                                 continue;
1058                                         }
1059
1060                                         int ws = valuePos;
1061                                         while (ws < s.Length) {
1062                                                 if (Char.IsWhiteSpace (s [ws]) || s [ws] == ',')
1063                                                         ws++;
1064                                                 else
1065                                                         break;
1066                                         }
1067                                         valuePos = ws;
1068                                         ws = pos;
1069                                         while (ws < chars.Length) {
1070                                                 if (Char.IsWhiteSpace (chars [ws]) || chars [ws] == ',')
1071                                                         ws++;
1072                                                 else
1073                                                         break;
1074                                         }
1075                                         pos = ws;
1076                                         continue;
1077                                 }
1078
1079                                 if ((pos+num+1 < len) && (chars[pos+num+1] == chars[pos+num])) {
1080                                         num++;
1081                                         continue;
1082                                 }
1083
1084
1085                                 int num_parsed = 0;
1086
1087                                 switch (chars[pos])
1088                                 {
1089                                 case 'd':
1090                                         if (day != -1)
1091                                                 return false;
1092                                         if (num == 0)
1093                                                 day = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1094                                         else if (num == 1)
1095                                                 day = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1096                                         else if (num == 2)
1097                                                 dayofweek = _ParseEnum (s, valuePos, dfi.RawAbbreviatedDayNames, out num_parsed);
1098                                         else
1099                                         {
1100                                                 dayofweek = _ParseEnum (s, valuePos, dfi.RawDayNames, out num_parsed);
1101                                                 num = 3;
1102                                         }
1103                                         break;
1104                                 case 'M':
1105                                         if (month != -1)
1106                                                 return false;
1107                                         if (num == 0)
1108                                                 month = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1109                                         else if (num == 1)
1110                                                 month = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1111                                         else if (num == 2)
1112                                                 month = _ParseEnum (s, valuePos, dfi.RawAbbreviatedMonthNames , out num_parsed) + 1;
1113                                         else
1114                                         {
1115                                                 month = _ParseEnum (s, valuePos, dfi.RawMonthNames, out num_parsed) + 1;
1116                                                 num = 3;
1117                                         }
1118                                         break;
1119                                 case 'y':
1120                                         if (year != -1)
1121                                                 return false;
1122
1123                                         if (num == 0) {
1124                                                 year = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1125                                         } else if (num < 3) {
1126                                                 year = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1127                                         } else {
1128                                                 year = _ParseNumber (s, valuePos,4, 4, false, sloppy_parsing, out num_parsed);
1129                                                 if ((year >= 1000) && (num_parsed == 4) && (!longYear) && (s.Length > 4 + valuePos)) {
1130                                                         int np = 0;
1131                                                         int ly = _ParseNumber (s, valuePos, 5, 5, false, sloppy_parsing, out np);
1132                                                         longYear = (ly > 9999);
1133                                                 }
1134                                                 num = 3;
1135                                         }
1136
1137                                         //FIXME: We should do use dfi.Calendat.TwoDigitYearMax
1138                                         if (num_parsed <= 2)
1139                                                 year += (year < 30) ? 2000 : 1900;
1140                                         break;
1141                                 case 'h':
1142                                         if (hour != -1)
1143                                                 return false;
1144                                         if (num == 0)
1145                                                 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1146                                         else
1147                                         {
1148                                                 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1149                                                 num = 1;
1150                                         }
1151
1152                                         if (hour > 12)
1153                                                 return false;
1154                                         if (hour == 12)
1155                                                 hour = 0;
1156
1157                                         break;
1158                                 case 'H':
1159                                         if ((hour != -1) || (ampm >= 0))
1160                                                 return false;
1161                                         if (num == 0)
1162                                                 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1163                                         else
1164                                         {
1165                                                 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1166                                                 num = 1;
1167                                         }
1168                                         if (hour >= 24)
1169                                                 return false;
1170
1171 //                                      ampm = -2;
1172                                         break;
1173                                 case 'm':
1174                                         if (minute != -1)
1175                                                 return false;
1176                                         if (num == 0)
1177                                                 minute = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1178                                         else
1179                                         {
1180                                                 minute = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1181                                                 num = 1;
1182                                         }
1183                                         if (minute >= 60)
1184                                                 return false;
1185
1186                                         break;
1187                                 case 's':
1188                                         if (second != -1)
1189                                                 return false;
1190                                         if (num == 0)
1191                                                 second = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1192                                         else
1193                                         {
1194                                                 second = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1195                                                 num = 1;
1196                                         }
1197                                         if (second >= 60)
1198                                                 return false;
1199
1200                                         break;
1201                                 case 'f':
1202                                         if (fractionalSeconds != -1)
1203                                                 return false;
1204                                         num = Math.Min (num, 6);
1205                                         double decimalNumber = (double) _ParseNumber (s, valuePos, 0, num+1, true, sloppy_parsing, out num_parsed);
1206                                         if (num_parsed == -1)
1207                                                 return false;
1208
1209                                         else
1210                                                 fractionalSeconds = decimalNumber / Math.Pow(10.0, num_parsed);
1211                                         break;
1212                                 case 't':
1213                                         if (ampm != -1)
1214                                                 return false;
1215                                         if (num == 0)
1216                                         {
1217                                                 if (_ParseString (s, valuePos, 1, dfi.AMDesignator, out num_parsed))
1218                                                         ampm = 0;
1219                                                 else if (_ParseString (s, valuePos, 1, dfi.PMDesignator, out num_parsed))
1220                                                         ampm = 1;
1221                                                 else
1222                                                         return false;
1223                                         }
1224                                         else
1225                                         {
1226                                                 if (_ParseString (s, valuePos, 0, dfi.AMDesignator, out num_parsed))
1227                                                         ampm = 0;
1228                                                 else if (_ParseString (s, valuePos, 0, dfi.PMDesignator, out num_parsed))
1229                                                         ampm = 1;
1230                                                 else
1231                                                         return false;
1232                                                 num = 1;
1233                                         }
1234                                         break;
1235                                 case 'z':
1236                                         if (tzsign != -1)
1237                                                 return false;
1238                                         if (s [valuePos] == '+')
1239                                                 tzsign = 0;
1240                                         else if (s [valuePos] == '-')
1241                                                 tzsign = 1;
1242                                         else
1243                                                 return false;
1244                                         valuePos++;
1245                                         if (num == 0)
1246                                                 tzoffset = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1247                                         else if (num == 1)
1248                                                 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1249                                         else
1250                                         {
1251                                                 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1252                                                 if (num_parsed < 0)
1253                                                         return false;
1254                                                 valuePos += num_parsed;
1255                                                 if (Char.IsDigit (s [valuePos]))
1256                                                         num_parsed = 0;
1257                                                 else if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1258                                                         return false;
1259                                                 valuePos += num_parsed;
1260                                                 tzoffmin = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1261                                                 if (num_parsed < 0)
1262                                                         return false;
1263                                                 num = 2;
1264                                         }
1265                                         break;
1266
1267                                 // LAMESPEC: This should be part of UTCpattern
1268                                 // string and thus should not be considered here.
1269                                 //
1270                                 // Note that 'Z' is not defined as a pattern
1271                                 // character. Keep it for X509 certificate
1272                                 // verification. Also, "Z" != "'Z'" under MS.NET
1273                                 // ("'Z'" is just literal; handled above)
1274                                 case 'Z':
1275                                         if (s [valuePos] != 'Z')
1276                                                 return false;
1277                                         num = 0;
1278                                         num_parsed = 1;
1279                                         useutc = true;
1280                                         break;
1281
1282                                 case ':':
1283                                         if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1284                                                 return false;
1285                                         break;
1286                                 case '/':
1287                                         /* Accept any character for
1288                                          * DateSeparator, except
1289                                          * TimeSeparator, a digit or a
1290                                          * letter.  Not documented,
1291                                          * but seems to be MS
1292                                          * behaviour here.  See bug
1293                                          * 54047.
1294                                          */
1295                                         if (exact && s [valuePos] != '/')
1296                                                 return false;
1297
1298                                         if (_ParseString (s, valuePos, 0,
1299                                                           dfi.TimeSeparator,
1300                                                           out num_parsed) ||
1301                                             Char.IsDigit (s [valuePos]) ||
1302                                             Char.IsLetter (s [valuePos])) {
1303                                                 return(false);
1304                                         }
1305
1306                                         num = 0;
1307                                         if (num_parsed <= 0) {
1308                                                 num_parsed = 1;
1309                                         }
1310                                         
1311                                         break;
1312                                 default:
1313                                         if (s [valuePos] != chars[pos]) {
1314                                                 // FIXME: It is not sure, but
1315                                                 // IsLetter() is introduced 
1316                                                 // because we have to reject 
1317                                                 // "2002a02b25" but have to
1318                                                 // allow "2002$02$25". The same
1319                                                 // thing applies to '/' case.
1320                                                 if (exact ||
1321                                                         Char.IsDigit (s [valuePos]) ||
1322                                                         Char.IsLetter (s [valuePos]))
1323                                                         return false;
1324                                         }
1325                                         num = 0;
1326                                         num_parsed = 1;
1327                                         break;
1328                                 }
1329
1330                                 if (num_parsed < 0)
1331                                         return false;
1332
1333                                 valuePos += num_parsed;
1334
1335                                 if (!exact) {
1336                                         switch (chars [pos]) {
1337                                         case 'm':
1338                                         case 's':
1339                                         case 'f':
1340                                         case 'z':
1341                                                 if (s.Length > valuePos && s [valuePos] == 'Z'
1342                                                     && (pos + 1 == chars.Length
1343                                                     || chars [pos + 1] != 'Z')) {
1344                                                         useutc = true;
1345                                                         valuePos++;
1346                                                 }
1347                                                 break;
1348                                         }
1349                                 }
1350
1351                                 pos = pos + num + 1;
1352                                 num = 0;
1353                         }
1354
1355                         // possible empty value. Regarded as no match.
1356                         if (pos == 0)
1357                                 return false;
1358
1359                         if (pos < len)
1360                                 return false;
1361
1362                         if (s.Length != valuePos) // extraneous tail.
1363                                 return false;
1364
1365                         if (hour == -1)
1366                                 hour = 0;
1367                         if (minute == -1)
1368                                 minute = 0;
1369
1370                         if (second == -1)
1371                                 second = 0;
1372                         if (fractionalSeconds == -1)
1373                                 fractionalSeconds = 0;
1374
1375                         // If no date was given
1376                         if ((day == -1) && (month == -1) && (year == -1)) {
1377                                 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
1378                                         day = 1;
1379                                         month = 1;
1380                                         year = 1;
1381                                 } else {
1382                                         day = Today.Day;
1383                                         month = Today.Month;
1384                                         year = Today.Year;
1385                                 }
1386                         }
1387
1388
1389                         if (day == -1)
1390                                 day = 1;
1391                         if (month == -1)
1392                                 month = 1;
1393                         if (year == -1) {
1394                                 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
1395                                         year = 1;
1396                                 else
1397                                         year = Today.Year;
1398                         }
1399
1400                         if (ampm == 1)
1401                                 hour = hour + 12;
1402                         
1403                         // For anything out of range 
1404                         // return false
1405                         if ( year < 1 || year > 9999 || 
1406                         month < 1 || month >12  ||
1407                         day < 1 || day > DaysInMonth(year, month) ||
1408                         hour < 0 || hour > 23 ||
1409                         minute < 0 || minute > 59 ||
1410                         second < 0 || second > 59 )
1411                                 return false;
1412
1413                         result = new DateTime (year, month, day, hour, minute, second, 0);
1414                         result = result.AddSeconds(fractionalSeconds);
1415
1416                         if ((dayofweek != -1) && (dayofweek != (int) result.DayOfWeek))
1417                                 throw new FormatException (Locale.GetText ("String was not recognized as valid DateTime because the day of week was incorrect."));
1418
1419                         // If no timezone was specified, default to the local timezone.
1420                         TimeSpan utcoffset;
1421
1422                         if (useutc) {
1423                                 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1424                                         use_localtime = false;
1425                                 utcoffset = new TimeSpan (0, 0, 0);
1426                         } else if (tzsign == -1) {
1427                                 TimeZone tz = TimeZone.CurrentTimeZone;
1428                                 utcoffset = tz.GetUtcOffset (result);
1429                         } else {
1430                                 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1431                                         use_localtime = false;
1432
1433                                 if (tzoffmin == -1)
1434                                         tzoffmin = 0;
1435                                 if (tzoffset == -1)
1436                                         tzoffset = 0;
1437                                 if (tzsign == 1)
1438                                         tzoffset = -tzoffset
1439 ;
1440                                 utcoffset = new TimeSpan (tzoffset, tzoffmin, 0);
1441                         }
1442
1443                         long newticks = (result.ticks - utcoffset).Ticks;
1444
1445                         result = new DateTime (false, new TimeSpan (newticks));
1446                         if (use_localtime)
1447                                 result = result.ToLocalTime ();
1448
1449                         return true;
1450                 }
1451
1452
1453                 public static DateTime ParseExact (string s, string format,
1454                                                    IFormatProvider fp, DateTimeStyles style)
1455                 {
1456                         string[] formats;
1457
1458                         formats = new string [1];
1459                         formats[0] = format;
1460
1461                         return ParseExact (s, formats, fp, style);
1462                 }
1463
1464                 public static DateTime ParseExact (string s, string[] formats,
1465                                                    IFormatProvider fp,
1466                                                    DateTimeStyles style)
1467                 {
1468                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1469
1470                         if (s == null)
1471                                 throw new ArgumentNullException (Locale.GetText ("s is null"));
1472                         if (formats == null || formats.Length == 0)
1473                                 throw new ArgumentNullException (Locale.GetText ("format is null"));
1474
1475                         DateTime result;
1476                         bool longYear = false;
1477                         if (!ParseExact (s, formats, dfi, style, out result, true, ref longYear))
1478                                 throw new FormatException ();
1479                         return result;
1480                 }
1481
1482 #if NET_2_0
1483                 public static bool TryParse (string s, out DateTime result)
1484                 {
1485                         try {
1486                                 result = Parse (s);
1487                         } catch {
1488                                 result = MinValue;
1489                                 return false;
1490                         }
1491                         return true;
1492                 }
1493                 
1494                 public static bool TryParse (string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
1495                 {
1496                         try {
1497                                 result = Parse (s, provider, styles);
1498                         } catch {
1499                                 result = MinValue;
1500                                 return false;
1501                         }
1502                         return true;
1503                 }
1504                 
1505                 public static bool TryParseExact (string s, string format,
1506                                                   IFormatProvider fp,
1507                                                   DateTimeStyles style,
1508                                                   out DateTime result)
1509                 {
1510                         string[] formats;
1511
1512                         formats = new string [1];
1513                         formats[0] = format;
1514
1515                         return TryParseExact (s, formats, fp, style, out result);
1516                 }
1517
1518                 public static bool TryParseExact (string s, string[] formats,
1519                                                   IFormatProvider fp,
1520                                                   DateTimeStyles style,
1521                                                   out DateTime result)
1522                 {
1523                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1524
1525                         bool longYear = false;
1526                         return ParseExact (s, formats, dfi, style, out result, true, ref longYear);
1527                 }
1528 #endif
1529
1530                 private static bool ParseExact (string s, string [] formats,
1531                         DateTimeFormatInfo dfi, DateTimeStyles style, out DateTime ret,
1532                         bool exact, ref bool longYear)
1533                 {
1534                         int i;
1535                         for (i = 0; i < formats.Length; i++)
1536                         {
1537                                 DateTime result;
1538
1539                                 if (_DoParse (s, formats[i], exact, out result, dfi, style, ref longYear)) {
1540                                         ret = result;
1541                                         return true;
1542                                 }
1543                         }
1544                         ret = DateTime.MinValue;
1545                         return false;
1546                 }
1547                 
1548                 public TimeSpan Subtract(DateTime dt)
1549                 {   
1550                         return new TimeSpan(ticks.Ticks) - dt.ticks;
1551                 }
1552
1553                 public DateTime Subtract(TimeSpan ts)
1554                 {
1555                         TimeSpan newticks;
1556
1557                         newticks = (new TimeSpan (ticks.Ticks)) - ts;
1558                         return new DateTime(true,newticks);
1559                 }
1560
1561                 public long ToFileTime()
1562                 {
1563                         DateTime universalTime = ToUniversalTime();
1564                         
1565                         if (universalTime.Ticks < w32file_epoch) {
1566                                 throw new ArgumentOutOfRangeException("file time is not valid");
1567                         }
1568                         
1569                         return(universalTime.Ticks - w32file_epoch);
1570                 }
1571
1572 #if NET_1_1
1573                 public long ToFileTimeUtc()
1574                 {
1575                         if (Ticks < w32file_epoch) {
1576                                 throw new ArgumentOutOfRangeException("file time is not valid");
1577                         }
1578                         
1579                         return (Ticks - w32file_epoch);
1580                 }
1581 #endif
1582
1583                 public string ToLongDateString()
1584                 {
1585                         return ToString ("D");
1586                 }
1587
1588                 public string ToLongTimeString()
1589                 {
1590                         return ToString ("T");
1591                 }
1592
1593                 public double ToOADate ()
1594                 {
1595                         long t = this.Ticks;
1596                         // uninitialized DateTime case
1597                         if (t == 0)
1598                                 return 0;
1599                         // we can't reach minimum value
1600                         if (t < 31242239136000000)
1601                                 return OAMinValue + 0.001;
1602
1603                         TimeSpan ts = new TimeSpan (this.Ticks - ticks18991230);
1604                         double result = ts.TotalDays;
1605                         // t < 0 (where 599264352000000000 == 0.0d for OA)
1606                         if (t < 599264352000000000) {
1607                                 // negative days (int) but decimals are positive
1608                                 double d = Math.Ceiling (result);
1609                                 result = d - 2 - (result - d);
1610                         }
1611                         else {
1612                                 // we can't reach maximum value
1613                                 if (result >= OAMaxValue)
1614                                         result = OAMaxValue - 0.00000001d;
1615                         }
1616                         return result;
1617                 }
1618
1619                 public string ToShortDateString()
1620                 {
1621                         return ToString ("d");
1622                 }
1623
1624                 public string ToShortTimeString()
1625                 {
1626                         return ToString ("t");
1627                 }
1628                 
1629                 public override string ToString ()
1630                 {
1631                         return ToString ("G", null);
1632                 }
1633
1634                 public string ToString (IFormatProvider fp)
1635                 {
1636                         return ToString (null, fp);
1637                 }
1638
1639                 public string ToString (string format)
1640                 {
1641                         return ToString (format, null);
1642                 }
1643
1644                 internal static string _GetStandardPattern (char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant)
1645                 {
1646                         String pattern;
1647
1648                         useutc = false;
1649                         use_invariant = false;
1650
1651                         switch (format)
1652                         {
1653                         case 'd':
1654                                 pattern = dfi.ShortDatePattern;
1655                                 break;
1656                         case 'D':
1657                                 pattern = dfi.LongDatePattern;
1658                                 break;
1659                         case 'f':
1660                                 pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
1661                                 break;
1662                         case 'F':
1663                                 pattern = dfi.FullDateTimePattern;
1664                                 break;
1665                         case 'g':
1666                                 pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
1667                                 break;
1668                         case 'G':
1669                                 pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
1670                                 break;
1671                         case 'm':
1672                         case 'M':
1673                                 pattern = dfi.MonthDayPattern;
1674                                 break;
1675                         case 'r':
1676                         case 'R':
1677                                 pattern = dfi.RFC1123Pattern;
1678                                 // commented by LP 09/jun/2002, rfc 1123 pattern is always in GMT
1679                                 // uncommented by AE 27/may/2004
1680 //                              useutc = true;
1681                                 use_invariant = true;
1682                                 break;
1683                         case 's':
1684                                 pattern = dfi.SortableDateTimePattern;
1685                                 break;
1686                         case 't':
1687                                 pattern = dfi.ShortTimePattern;
1688                                 break;
1689                         case 'T':
1690                                 pattern = dfi.LongTimePattern;
1691                                 break;
1692                         case 'u':
1693                                 pattern = dfi.UniversalSortableDateTimePattern;
1694                                 useutc = true;
1695                                 break;
1696                         case 'U':
1697 //                              pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
1698                                 pattern = dfi.FullDateTimePattern;
1699                                 useutc = true;
1700                                 break;
1701                         case 'y':
1702                         case 'Y':
1703                                 pattern = dfi.YearMonthPattern;
1704                                 break;
1705                         default:
1706                                 pattern = null;
1707                                 break;
1708                         }
1709
1710                         return pattern;
1711                 }
1712
1713                 internal string _ToString (string format, DateTimeFormatInfo dfi)
1714                 {
1715                         // the length of the format is usually a good guess of the number
1716                         // of chars in the result. Might save us a few bytes sometimes
1717                         // Add + 10 for cases like mmmm dddd
1718                         StringBuilder result = new StringBuilder (format.Length + 10);
1719
1720                         // For some cases, the output should not use culture dependent calendar
1721                         DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo;
1722                         if (format == inv.RFC1123Pattern)
1723                                 dfi = inv;
1724                         else if (format == inv.UniversalSortableDateTimePattern)
1725                                 dfi = inv;
1726
1727                         int i = 0;
1728
1729                         while (i < format.Length) {
1730                                 int tokLen;
1731                                 char ch = format [i];
1732
1733                                 switch (ch) {
1734
1735                                 //
1736                                 // Time Formats
1737                                 //
1738                                 case 'h':
1739                                         // hour, [1, 12]
1740                                         tokLen = CountRepeat (format, i, ch);
1741
1742                                         int hr = this.Hour % 12;
1743                                         if (hr == 0)
1744                                                 hr = 12;
1745
1746                                         ZeroPad (result, hr, tokLen == 1 ? 1 : 2);
1747                                         break;
1748                                 case 'H':
1749                                         // hour, [0, 23]
1750                                         tokLen = CountRepeat (format, i, ch);
1751                                         ZeroPad (result, this.Hour, tokLen == 1 ? 1 : 2);
1752                                         break;
1753                                 case 'm':
1754                                         // minute, [0, 59]
1755                                         tokLen = CountRepeat (format, i, ch);
1756                                         ZeroPad (result, this.Minute, tokLen == 1 ? 1 : 2);
1757                                         break;
1758                                 case 's':
1759                                         // second [0, 29]
1760                                         tokLen = CountRepeat (format, i, ch);
1761                                         ZeroPad (result, this.Second, tokLen == 1 ? 1 : 2);
1762                                         break;
1763                                 case 'f':
1764                                         // fraction of second, to same number of
1765                                         // digits as there are f's
1766
1767                                         tokLen = CountRepeat (format, i, ch);
1768                                         if (tokLen > 7)
1769                                                 throw new FormatException ("Invalid Format String");
1770
1771                                         int dec = (int)((long)(this.Ticks % TimeSpan.TicksPerSecond) / (long) Math.Pow (10, 7 - tokLen));
1772                                         ZeroPad (result, dec, tokLen);
1773
1774                                         break;
1775                                 case 't':
1776                                         // AM/PM. t == first char, tt+ == full
1777                                         tokLen = CountRepeat (format, i, ch);
1778                                         string desig = this.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator;
1779
1780                                         if (tokLen == 1) {
1781                                                 if (desig.Length >= 1)
1782                                                         result.Append (desig [0]);
1783                                         }
1784                                         else
1785                                                 result.Append (desig);
1786
1787                                         break;
1788                                 case 'z':
1789                                         // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm
1790                                         tokLen = CountRepeat (format, i, ch);
1791                                         TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset (this);
1792
1793                                         if (offset.Ticks >= 0)
1794                                                 result.Append ('+');
1795                                         else
1796                                                 result.Append ('-');
1797
1798                                         switch (tokLen) {
1799                                         case 1:
1800                                                 result.Append (Math.Abs (offset.Hours));
1801                                                 break;
1802                                         case 2:
1803                                                 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1804                                                 break;
1805                                         default:
1806                                                 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1807                                                 result.Append (':');
1808                                                 result.Append (Math.Abs (offset.Minutes).ToString ("00"));
1809                                                 break;
1810                                         }
1811                                         break;
1812                                 //
1813                                 // Date tokens
1814                                 //
1815                                 case 'd':
1816                                         // day. d(d?) = day of month (leading 0 if two d's)
1817                                         // ddd = three leter day of week
1818                                         // dddd+ full day-of-week
1819                                         tokLen = CountRepeat (format, i, ch);
1820
1821                                         if (tokLen <= 2)
1822                                                 ZeroPad (result, dfi.Calendar.GetDayOfMonth (this), tokLen == 1 ? 1 : 2);
1823                                         else if (tokLen == 3)
1824                                                 result.Append (dfi.GetAbbreviatedDayName (dfi.Calendar.GetDayOfWeek (this)));
1825                                         else
1826                                                 result.Append (dfi.GetDayName (dfi.Calendar.GetDayOfWeek (this)));
1827
1828                                         break;
1829                                 case 'M':
1830                                         // Month.m(m?) = month # (with leading 0 if two mm)
1831                                         // mmm = 3 letter name
1832                                         // mmmm+ = full name
1833                                         tokLen = CountRepeat (format, i, ch);
1834                                         int month = dfi.Calendar.GetMonth(this);
1835                                         if (tokLen <= 2)
1836                                                 ZeroPad (result, month, tokLen);
1837                                         else if (tokLen == 3)
1838                                                 result.Append (dfi.GetAbbreviatedMonthName (month));
1839                                         else
1840                                                 result.Append (dfi.GetMonthName (month));
1841
1842                                         break;
1843                                 case 'y':
1844                                         // Year. y(y?) = two digit year, with leading 0 if yy
1845                                         // yyy+ full year, if yyy and yr < 1000, displayed as three digits
1846                                         tokLen = CountRepeat (format, i, ch);
1847
1848                                         if (tokLen <= 2)
1849                                                 ZeroPad (result, dfi.Calendar.GetYear (this) % 100, tokLen);
1850                                         else
1851                                                 ZeroPad (result, dfi.Calendar.GetYear (this), (tokLen == 3 ? 3 : 4));
1852
1853                                         break;
1854                                 case 'g':
1855                                         // Era name
1856                                         tokLen = CountRepeat (format, i, ch);
1857                                         result.Append (dfi.GetEraName (dfi.Calendar.GetEra (this)));
1858                                         break;
1859
1860                                 //
1861                                 // Other
1862                                 //
1863                                 case ':':
1864                                         result.Append (dfi.TimeSeparator);
1865                                         tokLen = 1;
1866                                         break;
1867                                 case '/':
1868                                         result.Append (dfi.DateSeparator);
1869                                         tokLen = 1;
1870                                         break;
1871                                 case '\'': case '"':
1872                                         tokLen = ParseQuotedString (format, i, result);
1873                                         break;
1874                                 case '%':
1875                                         if (i >= format.Length - 1)
1876                                                 throw new FormatException ("% at end of date time string");
1877                                         if (format [i + 1] == '%')
1878                                                 throw new FormatException ("%% in date string");
1879
1880                                         // Look for the next char
1881                                         tokLen = 1;
1882                                         break;
1883                                 case '\\':
1884                                         // C-Style escape
1885                                         if (i >= format.Length - 1)
1886                                                 throw new FormatException ("\\ at end of date time string");
1887
1888                                         result.Append (format [i + 1]);
1889                                         tokLen = 2;
1890
1891                                         break;
1892                                 default:
1893                                         // catch all
1894                                         result.Append (ch);
1895                                         tokLen = 1;
1896                                         break;
1897                                 }
1898                                 i += tokLen;
1899                         }
1900                         return result.ToString ();
1901                 }
1902                 
1903                 static int CountRepeat (string fmt, int p, char c)
1904                 {
1905                         int l = fmt.Length;
1906                         int i = p + 1;
1907                         while ((i < l) && (fmt [i] == c)) 
1908                                 i++;
1909                         
1910                         return i - p;
1911                 }
1912                 
1913                 static int ParseQuotedString (string fmt, int pos, StringBuilder output)
1914                 {
1915                         // pos == position of " or '
1916                         
1917                         int len = fmt.Length;
1918                         int start = pos;
1919                         char quoteChar = fmt [pos++];
1920                         
1921                         while (pos < len) {
1922                                 char ch = fmt [pos++];
1923                                 
1924                                 if (ch == quoteChar)
1925                                         return pos - start;
1926                                 
1927                                 if (ch == '\\') {
1928                                         // C-Style escape
1929                                         if (pos >= len)
1930                                                 throw new FormatException("Un-ended quote");
1931         
1932                                         output.Append (fmt [pos++]);
1933                                 } else {
1934                                         output.Append (ch);
1935                                 }
1936                         }
1937
1938                         throw new FormatException("Un-ended quote");
1939                 }
1940                 
1941                 static unsafe void ZeroPad (StringBuilder output, int digits, int len)
1942                 {
1943                         // more than enough for an int
1944                         char* buffer = stackalloc char [16];
1945                         int pos = 16;
1946                         
1947                         do {
1948                                 buffer [-- pos] = (char) ('0' + digits % 10);
1949                                 digits /= 10;
1950                                 len --;
1951                         } while (digits > 0);
1952                         
1953                         while (len -- > 0)
1954                                 buffer [-- pos] = '0';
1955                         
1956                         output.Append (new string (buffer, pos, 16 - pos));
1957                 }
1958
1959                 public string ToString (string format, IFormatProvider fp)
1960
1961                 {
1962                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance(fp);
1963
1964                         if (format == null)
1965                                 format = "G";
1966
1967                         bool useutc = false, use_invariant = false;
1968
1969                         if (format.Length == 1) {
1970                                 char fchar = format [0];
1971                                 format = _GetStandardPattern (fchar, dfi, out useutc, out use_invariant);
1972                         }
1973
1974                         // Don't convert UTC value. It just adds 'Z' for 
1975                         // 'u' format, for the same ticks.
1976                         return this._ToString (format, dfi);
1977                 }
1978
1979                 public DateTime ToLocalTime ()
1980                 {
1981                         return TimeZone.CurrentTimeZone.ToLocalTime (this);
1982                 }
1983
1984                 public DateTime ToUniversalTime()
1985                 {
1986                         return TimeZone.CurrentTimeZone.ToUniversalTime (this);
1987                 }
1988
1989                 /*  OPERATORS */
1990
1991                 public static DateTime operator +(DateTime d, TimeSpan t)
1992                 {
1993                         return new DateTime (true, d.ticks + t);
1994                 }
1995
1996                 public static bool operator ==(DateTime d1, DateTime d2)
1997                 {
1998                         return (d1.ticks == d2.ticks);
1999                 }
2000
2001                 public static bool operator >(DateTime t1,DateTime t2)
2002                 {
2003                         return (t1.ticks > t2.ticks);
2004                 }
2005
2006                 public static bool operator >=(DateTime t1,DateTime t2)
2007                 {
2008                         return (t1.ticks >= t2.ticks);
2009                 }
2010
2011                 public static bool operator !=(DateTime d1, DateTime d2)
2012                 {
2013                         return (d1.ticks != d2.ticks);
2014                 }
2015
2016                 public static bool operator <(DateTime t1,      DateTime t2)
2017                 {
2018                         return (t1.ticks < t2.ticks );
2019                 }
2020
2021                 public static bool operator <=(DateTime t1,DateTime t2)
2022                 {
2023                         return (t1.ticks <= t2.ticks);
2024                 }
2025
2026                 public static TimeSpan operator -(DateTime d1,DateTime d2)
2027                 {
2028                         return new TimeSpan((d1.ticks - d2.ticks).Ticks);
2029                 }
2030
2031                 public static DateTime operator -(DateTime d,TimeSpan t)
2032                 {
2033                         return new DateTime (true, d.ticks - t);
2034                 }
2035
2036                 bool IConvertible.ToBoolean(IFormatProvider provider)
2037                 {
2038                         throw new InvalidCastException();
2039                 }
2040                 
2041                 byte IConvertible.ToByte(IFormatProvider provider)
2042                 {
2043                         throw new InvalidCastException();
2044
2045                 }
2046
2047                 char IConvertible.ToChar(IFormatProvider provider)
2048                 {
2049                         throw new InvalidCastException();
2050                 }
2051
2052                 System.DateTime IConvertible.ToDateTime(IFormatProvider provider)
2053                 {
2054                         return this;
2055                 } 
2056                 
2057                 decimal IConvertible.ToDecimal(IFormatProvider provider)
2058                 {
2059                          throw new InvalidCastException();
2060                 }
2061
2062                 double IConvertible.ToDouble(IFormatProvider provider)
2063                 {
2064                         throw new InvalidCastException();
2065                 }
2066
2067                 Int16 IConvertible.ToInt16(IFormatProvider provider)
2068                 {
2069                         throw new InvalidCastException();
2070                 }
2071
2072                 Int32 IConvertible.ToInt32(IFormatProvider provider)
2073                 {
2074                         throw new InvalidCastException();
2075                 }
2076
2077                 Int64 IConvertible.ToInt64(IFormatProvider provider)
2078                 {
2079                         throw new InvalidCastException();
2080                 }
2081
2082                 SByte IConvertible.ToSByte(IFormatProvider provider)
2083                 {
2084                         throw new InvalidCastException();
2085                 }
2086
2087                 Single IConvertible.ToSingle(IFormatProvider provider)
2088                 {
2089                         throw new InvalidCastException();
2090                 }
2091
2092                 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
2093                 {
2094                         if (conversionType == null)
2095                                 throw new ArgumentNullException ("conversionType");
2096
2097                         if (conversionType == typeof (DateTime))
2098                                 return this;
2099                         else if (conversionType == typeof (String))
2100                                 return this.ToString (provider);
2101                         else if (conversionType == typeof (Object))
2102                                 return this;
2103                         else
2104                                 throw new InvalidCastException();
2105                 }
2106
2107                 UInt16 IConvertible.ToUInt16(IFormatProvider provider)
2108                 {
2109                         throw new InvalidCastException();
2110                 }
2111                 
2112                 UInt32 IConvertible.ToUInt32(IFormatProvider provider)
2113                 {
2114                         throw new InvalidCastException();
2115                 }
2116
2117                 UInt64 IConvertible.ToUInt64(IFormatProvider provider)
2118                 {
2119                         throw new InvalidCastException();
2120                 }
2121         }
2122 }