2006-12-01 Atsushi Enomoto <atsushi@ximian.com>
[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-2005 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                                 return dt + (TimeSpan) to_local_time_span_object;
444                         }
445                 }
446
447                 public long Ticks
448                 { 
449                         get     
450                         { 
451                                 return ticks.Ticks;
452                         }
453                 }
454         
455                 public static DateTime Today 
456                 {
457                         get {
458                                 DateTime now = Now;
459                                 DateTime today = new DateTime (now.Year, now.Month, now.Day);
460 #if NET_2_0
461                                 today.kind = now.kind;
462 #endif
463                                 return today;
464                         }
465                 }
466
467                 public static DateTime UtcNow 
468                 {
469                         get {
470 #if NET_2_0
471                                 return new DateTime (GetNow (), DateTimeKind.Utc);
472 #else
473                                 return new DateTime (GetNow ());
474 #endif
475                         }
476                 }
477
478                 public int Year 
479                 {
480                         get 
481                         { 
482                                 return FromTicks(Which.Year); 
483                         }
484                 }
485
486 #if NET_2_0
487                 public DateTimeKind Kind {
488                         get {
489                                 return kind;
490                         }
491                 }
492 #endif
493
494                 /* methods */
495
496                 public DateTime Add (TimeSpan ts)
497                 {
498                         return AddTicks (ts.Ticks);
499                 }
500
501                 public DateTime AddDays (double days)
502                 {
503                         return AddMilliseconds (Math.Round (days * 86400000));
504                 }
505                 
506                 public DateTime AddTicks (long t)
507                 {
508                         if ((t + ticks.Ticks) > MAX_VALUE_TICKS || (t + ticks.Ticks) < 0) {
509                                 throw new ArgumentOutOfRangeException();
510                         }
511                         return new DateTime (t + ticks.Ticks);
512                 }
513
514                 public DateTime AddHours (double hours)
515                 {
516                         return AddMilliseconds (hours * 3600000);
517                 }
518
519                 public DateTime AddMilliseconds (double ms)
520                 {
521                         if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
522                                         (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
523                                 throw new ArgumentOutOfRangeException();
524                         }
525                         long msticks = (long) (ms * TimeSpan.TicksPerMillisecond);
526
527                         return AddTicks (msticks);
528                 }
529
530                 // required to match MS implementation for OADate (OLE Automation)
531                 private DateTime AddRoundedMilliseconds (double ms)
532                 {
533                         if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
534                                 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
535                                 throw new ArgumentOutOfRangeException ();
536                         }
537                         long msticks = (long) (ms += ms > 0 ? 0.5 : -0.5) * TimeSpan.TicksPerMillisecond;
538
539                         return AddTicks (msticks);
540                 }
541
542                 public DateTime AddMinutes (double minutes)
543                 {
544                         return AddMilliseconds (minutes * 60000);
545                 }
546                 
547                 public DateTime AddMonths (int months)
548                 {
549                         int day, month, year,  maxday ;
550                         DateTime temp ;
551
552                         day = this.Day;
553                         month = this.Month + (months % 12);
554                         year = this.Year + months/12 ;
555                         
556                         if (month < 1)
557                         {
558                                 month = 12 + month ;
559                                 year -- ;
560                         }
561                         else if (month>12) 
562                         {
563                                 month = month -12;
564                                 year ++;
565                         }
566                         maxday = DaysInMonth(year, month);
567                         if (day > maxday)
568                                 day = maxday;
569
570                         temp = new DateTime (year, month, day);
571                         return  temp.Add (this.TimeOfDay);
572                 }
573
574                 public DateTime AddSeconds (double seconds)
575                 {
576                         return AddMilliseconds (seconds*1000);
577                 }
578
579                 public DateTime AddYears (int years )
580                 {
581                         return AddMonths(years * 12);
582                 }
583
584                 public static int Compare (DateTime t1, DateTime t2)
585                 {
586                         if (t1.ticks < t2.ticks) 
587                                 return -1;
588                         else if (t1.ticks > t2.ticks) 
589                                 return 1;
590                         else
591                                 return 0;
592                 }
593
594                 public int CompareTo (object v)
595                 {
596                         if ( v == null)
597                                 return 1;
598
599                         if (!(v is System.DateTime))
600                                 throw new ArgumentException (Locale.GetText (
601                                         "Value is not a System.DateTime"));
602
603                         return Compare (this, (DateTime) v);
604                 }
605
606 #if NET_2_0
607                 public bool IsDaylightSavingTime ()
608                 {
609                         if (kind == DateTimeKind.Utc)
610                                 return false;
611                         return TimeZone.CurrentTimeZone.IsDaylightSavingTime (this);
612                 }
613
614                 public int CompareTo (DateTime value)
615                 {
616                         return Compare (this, value);
617                 }
618
619                 public bool Equals (DateTime value)
620                 {
621                         return value.ticks == ticks;
622                 }
623
624                 public static DateTime SpecifyKind (DateTime value, DateTimeKind kind)
625                 {
626                         return new DateTime (value.Ticks, kind);
627                 }
628 #endif
629
630                 public static int DaysInMonth (int year, int month)
631                 {
632                         int[] days ;
633
634                         if (month < 1 || month >12)
635                                 throw new ArgumentOutOfRangeException ();
636
637                         days = (IsLeapYear(year) ? daysmonthleap  : daysmonth);
638                         return days[month];                     
639                 }
640                 
641                 public override bool Equals (object o)
642                 {
643                         if (!(o is System.DateTime))
644                                 return false;
645
646                         return ((DateTime) o).ticks == ticks;
647                 }
648
649                 public static bool Equals (DateTime t1, DateTime t2 )
650                 {
651                         return (t1.ticks == t2.ticks );
652                 }
653
654                 public static DateTime FromFileTime (long fileTime) 
655                 {
656                         if (fileTime < 0)
657                                 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
658
659                         return new DateTime (w32file_epoch + fileTime).ToLocalTime ();
660                 }
661
662 #if NET_1_1
663                 public static DateTime FromFileTimeUtc (long fileTime) 
664                 {
665                         if (fileTime < 0)
666                                 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
667
668                         return new DateTime (w32file_epoch + fileTime);
669                 }
670 #endif
671
672                 public static DateTime FromOADate (double d)
673                 {
674                         // An OLE Automation date is implemented as a floating-point number
675                         // whose value is the number of days from midnight, 30 December 1899.
676
677                         // d must be negative 657435.0 through positive 2958466.0.
678                         if ((d <= OAMinValue) || (d >= OAMaxValue))
679                                 throw new ArgumentException ("d", "[-657435,2958466]");
680
681                         DateTime dt = new DateTime (ticks18991230);
682                         if (d < 0.0d) {
683                                 Double days = Math.Ceiling (d);
684                                 // integer part is the number of days (negative)
685                                 dt = dt.AddRoundedMilliseconds (days * 86400000);
686                                 // but decimals are the number of hours (in days fractions) and positive
687                                 Double hours = (days - d);
688                                 dt = dt.AddRoundedMilliseconds (hours * 86400000);
689                         }
690                         else {
691                                 dt = dt.AddRoundedMilliseconds (d * 86400000);
692                         }
693
694                         return dt;
695                 }
696
697                 public string[] GetDateTimeFormats() 
698                 {
699                         return GetDateTimeFormats (CultureInfo.CurrentCulture);
700                 }
701
702                 public string[] GetDateTimeFormats(char format)
703                 {
704                         if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
705                                 throw new FormatException ("Invalid format character.");
706                         string[] result = new string[1];
707                         result[0] = this.ToString(format.ToString());
708                         return result;
709                 }
710                 
711                 public string[] GetDateTimeFormats(IFormatProvider provider)
712                 {
713                         DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
714 //                      return GetDateTimeFormats (info.GetAllDateTimePatterns ());
715                         ArrayList al = new ArrayList ();
716                         foreach (char c in "dDgGfFmMrRstTuUyY")
717                                 al.AddRange (GetDateTimeFormats (c, info));
718                         return al.ToArray (typeof (string)) as string [];
719                 }
720
721                 public string[] GetDateTimeFormats(char format,IFormatProvider provider )
722                 {
723                         if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
724                                 throw new FormatException ("Invalid format character.");
725
726                         // LAMESPEC: There is NO assurance that 'U' ALWAYS
727                         // euqals to 'F', but since we have to iterate all
728                         // the pattern strings, we cannot just use 
729                         // ToString("U", provider) here. I believe that the 
730                         // method's behavior cannot be formalized.
731                         bool adjustutc = false;
732                         switch (format) {
733                         case 'U':
734 //                      case 'r':
735 //                      case 'R':
736 //                      case 'u':
737                                 adjustutc = true;
738                                 break;
739                         }
740                         DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
741                         return GetDateTimeFormats (adjustutc, info.GetAllRawDateTimePatterns (format), info);
742                 }
743
744                 private string [] GetDateTimeFormats (bool adjustutc, string [] patterns, DateTimeFormatInfo dfi)
745                 {
746                         string [] results = new string [patterns.Length];
747                         DateTime val = adjustutc ? ToUniversalTime () : this;
748                         for (int i = 0; i < results.Length; i++)
749                                 results [i] = val._ToString (patterns [i], dfi);
750                         return results;
751                 }
752
753 #if NET_2_0
754                 private void CheckDateTimeKind (DateTimeKind kind) {
755                         if ((kind != DateTimeKind.Unspecified) && (kind != DateTimeKind.Utc) && (kind != DateTimeKind.Local))
756                                 throw new ArgumentException ("Invalid DateTimeKind value.", "kind");
757                 }
758 #endif
759
760                 public override int GetHashCode ()
761                 {
762                         return (int) ticks.Ticks;
763                 }
764
765                 public TypeCode GetTypeCode ()
766                 {
767                         return TypeCode.DateTime;
768                 }
769
770                 public static bool IsLeapYear (int year)
771                 {
772                         return  ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
773                 }
774
775                 public static DateTime Parse (string s)
776                 {
777                         return Parse (s, null);
778                 }
779
780                 public static DateTime Parse (string s, IFormatProvider fp)
781                 {
782                         return Parse (s, fp, DateTimeStyles.AllowWhiteSpaces);
783                 }
784
785                 public static DateTime Parse (string s, IFormatProvider fp, DateTimeStyles styles)
786                 {
787                         // This method should try only expected patterns. 
788                         // Should not try extra patterns.
789                         // Right now we also try InvariantCulture, but I
790                         // confirmed in some cases this method rejects what
791                         // InvariantCulture supports (can be checked against
792                         // "th-TH" with Gregorian Calendar). So basically it
793                         // should not be done.
794                         // I think it should be CurrentCulture to be tested,
795                         // but right now we don't support all the supported
796                         // patterns for each culture, so try InvariantCulture
797                         // as a quick remedy.
798                         if (s == null)
799                                 throw new ArgumentNullException (Locale.GetText ("s is null"));
800                         DateTime result;
801
802                         if (fp == null)
803                                 fp = CultureInfo.CurrentCulture;
804                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
805
806                         bool longYear = false;
807
808                         // Try all the patterns
809                         if (ParseExact (s, dfi.GetAllDateTimePatternsInternal (), dfi, styles, out result, false, ref longYear))
810                                 return result;
811
812                         // Try common formats.
813 //                      if (ParseExact (s, commonFormats, dfi, styles, out result, false, ref longYear))
814 //                              return result;
815
816                         // Try common formats with invariant culture
817                         if (ParseExact (s, commonFormats, DateTimeFormatInfo.InvariantInfo, styles, out result, false, ref longYear))
818                                 return result;
819
820                         if (longYear) {
821                                 throw new ArgumentOutOfRangeException ("year",
822                                         "Valid values are between 1 and 9999 inclusive");
823                         }
824
825                         throw new FormatException ("String was not recognized as a valid DateTime.");
826                 }
827
828                 public static DateTime ParseExact (string s, string format, IFormatProvider fp)
829                 {
830                         return ParseExact (s, format, fp, DateTimeStyles.None);
831                 }
832
833                 internal static int _ParseNumber (string s, int valuePos,
834                                                   int min_digits,
835                                                   int digits,
836                                                   bool leadingzero,
837                                                   bool sloppy_parsing,
838                                                   out int num_parsed)
839                 {
840                         int number = 0, i;
841
842                         if (sloppy_parsing)
843                                 leadingzero = false;
844
845                         if (!leadingzero) {
846                                 int real_digits = 0;
847                                 for (i = valuePos; i < s.Length && i < digits + valuePos; i++) {
848                                         if (!Char.IsDigit (s[i]))
849                                                 break;
850
851                                         real_digits++;
852                                 }
853
854                                 digits = real_digits;
855                         }
856                         if (digits < min_digits) {
857                                 num_parsed = -1;
858                                 return 0;
859                         }
860
861                         if (s.Length - valuePos < digits) {
862                                 num_parsed = -1;
863                                 return 0;
864                         }
865
866                         for (i = valuePos; i < digits + valuePos; i++) {
867                                 char c = s[i];
868                                 if (!Char.IsDigit (c)) {
869                                         num_parsed = -1;
870                                         return 0;
871                                 }
872
873                                 number = number * 10 + (byte) (c - '0');
874                         }
875
876                         num_parsed = digits;
877                         return number;
878                 }
879
880                 internal static int _ParseEnum (string s, int sPos, string[] values, out int num_parsed)
881                 {
882                         int i;
883
884                         for (i = 0; i < values.Length; i++) {
885                                 if (s.Length - sPos < values[i].Length)
886                                         continue;
887                                 else if (values [i].Length == 0)
888                                         continue;
889                                 String tmp = s.Substring (sPos, values[i].Length);
890                                 if (String.Compare (tmp, values[i], true) == 0) {
891                                         num_parsed = values[i].Length;
892                                         return i;
893                                 }
894                         }
895
896                         num_parsed = -1;
897                         return -1;
898                 }
899
900                 internal static bool _ParseString (string s, int sPos, int maxlength, string value, out int num_parsed)
901                 {
902                         if (maxlength <= 0)
903                                 maxlength = value.Length;
904
905                         if (String.Compare (s, sPos, value, 0, maxlength, true, CultureInfo.InvariantCulture) == 0) {
906                                 num_parsed = maxlength;
907                                 return true;
908                         }
909
910                         num_parsed = -1;
911                         return false;
912                 }
913
914                 private static bool _DoParse (string s, string format, bool exact,
915                                                out DateTime result,
916                                                DateTimeFormatInfo dfi,
917                                                DateTimeStyles style,
918                                                ref bool longYear)
919                 {
920                         bool useutc = false, use_localtime = true;
921                         bool use_invariant = false;
922                         bool sloppy_parsing = false;
923                         int valuePos = 0;
924                         if (format.Length == 1)
925                                 format = _GetStandardPattern (format [0], dfi, out useutc, out use_invariant);
926                         else if (!exact && CultureInfo.InvariantCulture.CompareInfo.IndexOf (format, "GMT", CompareOptions.Ordinal) >= 0)
927                                 useutc = true;
928
929                         if ((style & DateTimeStyles.AllowLeadingWhite) != 0) {
930                                 format = format.TrimStart (null);
931
932                                 s = s.TrimStart (null); // it could be optimized, but will make little good.
933                         }
934
935                         if ((style & DateTimeStyles.AllowTrailingWhite) != 0) {
936                                 format = format.TrimEnd (null);
937                                 s = s.TrimEnd (null); // it could be optimized, but will make little good.
938                         }
939
940                         if (use_invariant)
941                                 dfi = DateTimeFormatInfo.InvariantInfo;
942
943                         if ((style & DateTimeStyles.AllowInnerWhite) != 0)
944                                 sloppy_parsing = true;
945
946                         string chars = format;
947                         int len = format.Length, pos = 0, num = 0;
948
949                         int day = -1, dayofweek = -1, month = -1, year = -1;
950                         int hour = -1, minute = -1, second = -1;
951                         double fractionalSeconds = -1;
952                         int ampm = -1;
953                         int tzsign = -1, tzoffset = -1, tzoffmin = -1;
954
955                         result = new DateTime (0);
956                         while (pos+num < len)
957                         {
958                                 if (s.Length == valuePos)
959                                         break;
960
961                                 if (chars[pos] == '\'') {
962                                         num = 1;
963                                         while (pos+num < len) {
964                                                 if (chars[pos+num] == '\'')
965                                                         break;
966
967                                                 if (valuePos == s.Length)
968                                                         return false;
969                                                 if (s [valuePos] != chars [pos + num])
970                                                         return false;
971                                                 valuePos++;
972
973                                                 num++;
974                                         }
975                                         if (pos+num > len)
976                                                 return false;
977
978                                         pos += num + 1;
979                                         num = 0;
980                                         continue;
981                                 } else if (chars[pos] == '"') {
982                                         num = 1;
983                                         while (pos+num < len) {
984                                                 if (chars[pos+num] == '"')
985                                                         break;
986
987                                                 if (valuePos == s.Length)
988                                                         return false;
989                                                 if (s [valuePos] != chars[pos+num])
990                                                         return false;
991                                                 valuePos++;
992
993                                                 num++;
994                                         }
995                                         if (pos+num > len)
996                                                 return false;
997
998                                         pos += num + 1;
999                                         num = 0;
1000                                         continue;
1001                                 } else if (chars[pos] == '\\') {
1002                                         pos += num + 1;
1003                                         num = 0;
1004                                         if (pos >= len)
1005                                                 return false;
1006
1007                                         if (s [valuePos] != chars [pos])
1008                                                 return false;
1009                                         valuePos++;
1010                                         pos++;
1011                                         continue;
1012                                 } else if (chars[pos] == '%') {
1013                                         pos++;
1014                                         continue;
1015                                 } else if (Char.IsWhiteSpace (s [valuePos]) ||
1016                                         s [valuePos] == ',' && Char.IsWhiteSpace (chars [pos])) {
1017                                         valuePos++;
1018                                         num = 0;
1019                                         if (exact && (style & DateTimeStyles.AllowInnerWhite) == 0) {
1020                                                 if (!Char.IsWhiteSpace (chars[pos]))
1021                                                         return false;
1022                                                 pos++;
1023                                                 continue;
1024                                         }
1025
1026                                         int ws = valuePos;
1027                                         while (ws < s.Length) {
1028                                                 if (Char.IsWhiteSpace (s [ws]) || s [ws] == ',')
1029                                                         ws++;
1030                                                 else
1031                                                         break;
1032                                         }
1033                                         valuePos = ws;
1034                                         ws = pos;
1035                                         while (ws < chars.Length) {
1036                                                 if (Char.IsWhiteSpace (chars [ws]) || chars [ws] == ',')
1037                                                         ws++;
1038                                                 else
1039                                                         break;
1040                                         }
1041                                         pos = ws;
1042                                         continue;
1043                                 }
1044
1045                                 if ((pos+num+1 < len) && (chars[pos+num+1] == chars[pos+num])) {
1046                                         num++;
1047                                         continue;
1048                                 }
1049
1050
1051                                 int num_parsed = 0;
1052
1053                                 switch (chars[pos])
1054                                 {
1055                                 case 'd':
1056                                         if (day != -1)
1057                                                 return false;
1058                                         if (num == 0)
1059                                                 day = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1060                                         else if (num == 1)
1061                                                 day = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1062                                         else if (num == 2)
1063                                                 dayofweek = _ParseEnum (s, valuePos, dfi.RawAbbreviatedDayNames, out num_parsed);
1064                                         else
1065                                         {
1066                                                 dayofweek = _ParseEnum (s, valuePos, dfi.RawDayNames, out num_parsed);
1067                                                 num = 3;
1068                                         }
1069                                         break;
1070                                 case 'M':
1071                                         if (month != -1)
1072                                                 return false;
1073                                         if (num == 0)
1074                                                 month = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1075                                         else if (num == 1)
1076                                                 month = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1077                                         else if (num == 2)
1078                                                 month = _ParseEnum (s, valuePos, dfi.RawAbbreviatedMonthNames , out num_parsed) + 1;
1079                                         else
1080                                         {
1081                                                 month = _ParseEnum (s, valuePos, dfi.RawMonthNames, out num_parsed) + 1;
1082                                                 num = 3;
1083                                         }
1084                                         break;
1085                                 case 'y':
1086                                         if (year != -1)
1087                                                 return false;
1088
1089                                         if (num == 0) {
1090                                                 year = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1091                                         } else if (num < 3) {
1092                                                 year = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1093                                         } else {
1094                                                 year = _ParseNumber (s, valuePos,4, 4, false, sloppy_parsing, out num_parsed);
1095                                                 if ((year >= 1000) && (num_parsed == 4) && (!longYear) && (s.Length > 4 + valuePos)) {
1096                                                         int np = 0;
1097                                                         int ly = _ParseNumber (s, valuePos, 5, 5, false, sloppy_parsing, out np);
1098                                                         longYear = (ly > 9999);
1099                                                 }
1100                                                 num = 3;
1101                                         }
1102
1103                                         //FIXME: We should do use dfi.Calendat.TwoDigitYearMax
1104                                         if (num_parsed <= 2)
1105                                                 year += (year < 30) ? 2000 : 1900;
1106                                         break;
1107                                 case 'h':
1108                                         if (hour != -1)
1109                                                 return false;
1110                                         if (num == 0)
1111                                                 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1112                                         else
1113                                         {
1114                                                 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1115                                                 num = 1;
1116                                         }
1117
1118                                         if (hour > 12)
1119                                                 return false;
1120                                         if (hour == 12)
1121                                                 hour = 0;
1122
1123                                         break;
1124                                 case 'H':
1125                                         if ((hour != -1) || (ampm >= 0))
1126                                                 return false;
1127                                         if (num == 0)
1128                                                 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1129                                         else
1130                                         {
1131                                                 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1132                                                 num = 1;
1133                                         }
1134                                         if (hour >= 24)
1135                                                 return false;
1136
1137 //                                      ampm = -2;
1138                                         break;
1139                                 case 'm':
1140                                         if (minute != -1)
1141                                                 return false;
1142                                         if (num == 0)
1143                                                 minute = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1144                                         else
1145                                         {
1146                                                 minute = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1147                                                 num = 1;
1148                                         }
1149                                         if (minute >= 60)
1150                                                 return false;
1151
1152                                         break;
1153                                 case 's':
1154                                         if (second != -1)
1155                                                 return false;
1156                                         if (num == 0)
1157                                                 second = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1158                                         else
1159                                         {
1160                                                 second = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1161                                                 num = 1;
1162                                         }
1163                                         if (second >= 60)
1164                                                 return false;
1165
1166                                         break;
1167                                 case 'f':
1168                                         if (fractionalSeconds != -1)
1169                                                 return false;
1170                                         num = Math.Min (num, 6);
1171                                         double decimalNumber = (double) _ParseNumber (s, valuePos, 0, num+1, true, sloppy_parsing, out num_parsed);
1172                                         if (num_parsed == -1)
1173                                                 return false;
1174
1175                                         else
1176                                                 fractionalSeconds = decimalNumber / Math.Pow(10.0, num_parsed);
1177                                         break;
1178                                 case 't':
1179                                         if (ampm != -1)
1180                                                 return false;
1181                                         if (num == 0)
1182                                         {
1183                                                 if (_ParseString (s, valuePos, 1, dfi.AMDesignator, out num_parsed))
1184                                                         ampm = 0;
1185                                                 else if (_ParseString (s, valuePos, 1, dfi.PMDesignator, out num_parsed))
1186                                                         ampm = 1;
1187                                                 else
1188                                                         return false;
1189                                         }
1190                                         else
1191                                         {
1192                                                 if (_ParseString (s, valuePos, 0, dfi.AMDesignator, out num_parsed))
1193                                                         ampm = 0;
1194                                                 else if (_ParseString (s, valuePos, 0, dfi.PMDesignator, out num_parsed))
1195                                                         ampm = 1;
1196                                                 else
1197                                                         return false;
1198                                                 num = 1;
1199                                         }
1200                                         break;
1201                                 case 'z':
1202                                         if (tzsign != -1)
1203                                                 return false;
1204                                         if (s [valuePos] == '+')
1205                                                 tzsign = 0;
1206                                         else if (s [valuePos] == '-')
1207                                                 tzsign = 1;
1208                                         else
1209                                                 return false;
1210                                         valuePos++;
1211                                         if (num == 0)
1212                                                 tzoffset = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1213                                         else if (num == 1)
1214                                                 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1215                                         else
1216                                         {
1217                                                 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1218                                                 if (num_parsed < 0)
1219                                                         return false;
1220                                                 valuePos += num_parsed;
1221                                                 if (Char.IsDigit (s [valuePos]))
1222                                                         num_parsed = 0;
1223                                                 else if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1224                                                         return false;
1225                                                 valuePos += num_parsed;
1226                                                 tzoffmin = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1227                                                 if (num_parsed < 0)
1228                                                         return false;
1229                                                 num = 2;
1230                                         }
1231                                         break;
1232
1233                                 // LAMESPEC: This should be part of UTCpattern
1234                                 // string and thus should not be considered here.
1235                                 //
1236                                 // Note that 'Z' is not defined as a pattern
1237                                 // character. Keep it for X509 certificate
1238                                 // verification. Also, "Z" != "'Z'" under MS.NET
1239                                 // ("'Z'" is just literal; handled above)
1240                                 case 'Z':
1241                                         if (s [valuePos] != 'Z')
1242                                                 return false;
1243                                         num = 0;
1244                                         num_parsed = 1;
1245                                         useutc = true;
1246                                         break;
1247
1248                                 case ':':
1249                                         if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1250                                                 return false;
1251                                         break;
1252                                 case '/':
1253                                         /* Accept any character for
1254                                          * DateSeparator, except
1255                                          * TimeSeparator, a digit or a
1256                                          * letter.  Not documented,
1257                                          * but seems to be MS
1258                                          * behaviour here.  See bug
1259                                          * 54047.
1260                                          */
1261                                         if (exact && s [valuePos] != '/')
1262                                                 return false;
1263
1264                                         if (_ParseString (s, valuePos, 0,
1265                                                           dfi.TimeSeparator,
1266                                                           out num_parsed) ||
1267                                             Char.IsDigit (s [valuePos]) ||
1268                                             Char.IsLetter (s [valuePos])) {
1269                                                 return(false);
1270                                         }
1271
1272                                         num = 0;
1273                                         if (num_parsed <= 0) {
1274                                                 num_parsed = 1;
1275                                         }
1276                                         
1277                                         break;
1278                                 default:
1279                                         if (s [valuePos] != chars[pos]) {
1280                                                 // FIXME: It is not sure, but
1281                                                 // IsLetter() is introduced 
1282                                                 // because we have to reject 
1283                                                 // "2002a02b25" but have to
1284                                                 // allow "2002$02$25". The same
1285                                                 // thing applies to '/' case.
1286                                                 if (exact ||
1287                                                         Char.IsDigit (s [valuePos]) ||
1288                                                         Char.IsLetter (s [valuePos]))
1289                                                         return false;
1290                                         }
1291                                         num = 0;
1292                                         num_parsed = 1;
1293                                         break;
1294                                 }
1295
1296                                 if (num_parsed < 0)
1297                                         return false;
1298
1299                                 valuePos += num_parsed;
1300
1301                                 if (!exact) {
1302                                         switch (chars [pos]) {
1303                                         case 'm':
1304                                         case 's':
1305                                         case 'f':
1306                                         case 'z':
1307                                                 if (s.Length > valuePos && s [valuePos] == 'Z'
1308                                                     && (pos + 1 == chars.Length
1309                                                     || chars [pos + 1] != 'Z')) {
1310                                                         useutc = true;
1311                                                         valuePos++;
1312                                                 }
1313                                                 break;
1314                                         }
1315                                 }
1316
1317                                 pos = pos + num + 1;
1318                                 num = 0;
1319                         }
1320
1321                         // possible empty value. Regarded as no match.
1322                         if (pos == 0)
1323                                 return false;
1324
1325                         if (pos < len)
1326                                 return false;
1327
1328                         if (s.Length != valuePos) // extraneous tail.
1329                                 return false;
1330
1331                         if (hour == -1)
1332                                 hour = 0;
1333                         if (minute == -1)
1334                                 minute = 0;
1335
1336                         if (second == -1)
1337                                 second = 0;
1338                         if (fractionalSeconds == -1)
1339                                 fractionalSeconds = 0;
1340
1341                         // If no date was given
1342                         if ((day == -1) && (month == -1) && (year == -1)) {
1343                                 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
1344                                         day = 1;
1345                                         month = 1;
1346                                         year = 1;
1347                                 } else {
1348                                         day = Today.Day;
1349                                         month = Today.Month;
1350                                         year = Today.Year;
1351                                 }
1352                         }
1353
1354
1355                         if (day == -1)
1356                                 day = 1;
1357                         if (month == -1)
1358                                 month = 1;
1359                         if (year == -1) {
1360                                 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
1361                                         year = 1;
1362                                 else
1363                                         year = Today.Year;
1364                         }
1365
1366                         if (ampm == 1)
1367                                 hour = hour + 12;
1368                         
1369                         // For anything out of range 
1370                         // return false
1371                         if ( year < 1 || year > 9999 || 
1372                         month < 1 || month >12  ||
1373                         day < 1 || day > DaysInMonth(year, month) ||
1374                         hour < 0 || hour > 23 ||
1375                         minute < 0 || minute > 59 ||
1376                         second < 0 || second > 59 )
1377                                 return false;
1378
1379                         result = new DateTime (year, month, day, hour, minute, second, 0);
1380                         result = result.AddSeconds(fractionalSeconds);
1381
1382                         if ((dayofweek != -1) && (dayofweek != (int) result.DayOfWeek))
1383                                 throw new FormatException (Locale.GetText ("String was not recognized as valid DateTime because the day of week was incorrect."));
1384
1385                         // If no timezone was specified, default to the local timezone.
1386                         TimeSpan utcoffset;
1387
1388                         if (useutc) {
1389                                 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1390                                         use_localtime = false;
1391                                 utcoffset = new TimeSpan (0, 0, 0);
1392                         } else if (tzsign == -1) {
1393                                 TimeZone tz = TimeZone.CurrentTimeZone;
1394                                 utcoffset = tz.GetUtcOffset (result);
1395                         } else {
1396                                 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1397                                         use_localtime = false;
1398
1399                                 if (tzoffmin == -1)
1400                                         tzoffmin = 0;
1401                                 if (tzoffset == -1)
1402                                         tzoffset = 0;
1403                                 if (tzsign == 1)
1404                                         tzoffset = -tzoffset
1405 ;
1406                                 utcoffset = new TimeSpan (tzoffset, tzoffmin, 0);
1407                         }
1408
1409                         long newticks = (result.ticks - utcoffset).Ticks;
1410
1411                         result = new DateTime (false, new TimeSpan (newticks));
1412                         if (use_localtime)
1413                                 result = result.ToLocalTime ();
1414
1415                         return true;
1416                 }
1417
1418
1419                 public static DateTime ParseExact (string s, string format,
1420                                                    IFormatProvider fp, DateTimeStyles style)
1421                 {
1422                         string[] formats;
1423
1424                         formats = new string [1];
1425                         formats[0] = format;
1426
1427                         return ParseExact (s, formats, fp, style);
1428                 }
1429
1430                 public static DateTime ParseExact (string s, string[] formats,
1431                                                    IFormatProvider fp,
1432                                                    DateTimeStyles style)
1433                 {
1434                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1435
1436                         if (s == null)
1437                                 throw new ArgumentNullException (Locale.GetText ("s is null"));
1438                         if (formats == null || formats.Length == 0)
1439                                 throw new ArgumentNullException (Locale.GetText ("format is null"));
1440
1441                         DateTime result;
1442                         bool longYear = false;
1443                         if (!ParseExact (s, formats, dfi, style, out result, true, ref longYear))
1444                                 throw new FormatException ();
1445                         return result;
1446                 }
1447
1448 #if NET_2_0
1449                 public static bool TryParse (string s, out DateTime result)
1450                 {
1451                         try {
1452                                 result = Parse (s);
1453                         } catch {
1454                                 result = MinValue;
1455                                 return false;
1456                         }
1457                         return true;
1458                 }
1459                 
1460                 public static bool TryParse (string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
1461                 {
1462                         try {
1463                                 result = Parse (s, provider, styles);
1464                         } catch {
1465                                 result = MinValue;
1466                                 return false;
1467                         }
1468                         return true;
1469                 }
1470                 
1471                 public static bool TryParseExact (string s, string format,
1472                                                   IFormatProvider fp,
1473                                                   DateTimeStyles style,
1474                                                   out DateTime result)
1475                 {
1476                         string[] formats;
1477
1478                         formats = new string [1];
1479                         formats[0] = format;
1480
1481                         return TryParseExact (s, formats, fp, style, out result);
1482                 }
1483
1484                 public static bool TryParseExact (string s, string[] formats,
1485                                                   IFormatProvider fp,
1486                                                   DateTimeStyles style,
1487                                                   out DateTime result)
1488                 {
1489                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1490
1491                         bool longYear = false;
1492                         return ParseExact (s, formats, dfi, style, out result, true, ref longYear);
1493                 }
1494 #endif
1495
1496                 private static bool ParseExact (string s, string [] formats,
1497                         DateTimeFormatInfo dfi, DateTimeStyles style, out DateTime ret,
1498                         bool exact, ref bool longYear)
1499                 {
1500                         int i;
1501                         for (i = 0; i < formats.Length; i++)
1502                         {
1503                                 DateTime result;
1504
1505                                 if (_DoParse (s, formats[i], exact, out result, dfi, style, ref longYear)) {
1506                                         ret = result;
1507                                         return true;
1508                                 }
1509                         }
1510                         ret = DateTime.MinValue;
1511                         return false;
1512                 }
1513                 
1514                 public TimeSpan Subtract(DateTime dt)
1515                 {   
1516                         return new TimeSpan(ticks.Ticks) - dt.ticks;
1517                 }
1518
1519                 public DateTime Subtract(TimeSpan ts)
1520                 {
1521                         TimeSpan newticks;
1522
1523                         newticks = (new TimeSpan (ticks.Ticks)) - ts;
1524                         return new DateTime(true,newticks);
1525                 }
1526
1527                 public long ToFileTime()
1528                 {
1529                         DateTime universalTime = ToUniversalTime();
1530                         
1531                         if (universalTime.Ticks < w32file_epoch) {
1532                                 throw new ArgumentOutOfRangeException("file time is not valid");
1533                         }
1534                         
1535                         return(universalTime.Ticks - w32file_epoch);
1536                 }
1537
1538 #if NET_1_1
1539                 public long ToFileTimeUtc()
1540                 {
1541                         if (Ticks < w32file_epoch) {
1542                                 throw new ArgumentOutOfRangeException("file time is not valid");
1543                         }
1544                         
1545                         return (Ticks - w32file_epoch);
1546                 }
1547 #endif
1548
1549                 public string ToLongDateString()
1550                 {
1551                         return ToString ("D");
1552                 }
1553
1554                 public string ToLongTimeString()
1555                 {
1556                         return ToString ("T");
1557                 }
1558
1559                 public double ToOADate ()
1560                 {
1561                         long t = this.Ticks;
1562                         // uninitialized DateTime case
1563                         if (t == 0)
1564                                 return 0;
1565                         // we can't reach minimum value
1566                         if (t < 31242239136000000)
1567                                 return OAMinValue + 0.001;
1568
1569                         TimeSpan ts = new TimeSpan (this.Ticks - ticks18991230);
1570                         double result = ts.TotalDays;
1571                         // t < 0 (where 599264352000000000 == 0.0d for OA)
1572                         if (t < 599264352000000000) {
1573                                 // negative days (int) but decimals are positive
1574                                 double d = Math.Ceiling (result);
1575                                 result = d - 2 - (result - d);
1576                         }
1577                         else {
1578                                 // we can't reach maximum value
1579                                 if (result >= OAMaxValue)
1580                                         result = OAMaxValue - 0.00000001d;
1581                         }
1582                         return result;
1583                 }
1584
1585                 public string ToShortDateString()
1586                 {
1587                         return ToString ("d");
1588                 }
1589
1590                 public string ToShortTimeString()
1591                 {
1592                         return ToString ("t");
1593                 }
1594                 
1595                 public override string ToString ()
1596                 {
1597                         return ToString ("G", null);
1598                 }
1599
1600                 public string ToString (IFormatProvider fp)
1601                 {
1602                         return ToString (null, fp);
1603                 }
1604
1605                 public string ToString (string format)
1606                 {
1607                         return ToString (format, null);
1608                 }
1609
1610                 internal static string _GetStandardPattern (char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant)
1611                 {
1612                         String pattern;
1613
1614                         useutc = false;
1615                         use_invariant = false;
1616
1617                         switch (format)
1618                         {
1619                         case 'd':
1620                                 pattern = dfi.ShortDatePattern;
1621                                 break;
1622                         case 'D':
1623                                 pattern = dfi.LongDatePattern;
1624                                 break;
1625                         case 'f':
1626                                 pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
1627                                 break;
1628                         case 'F':
1629                                 pattern = dfi.FullDateTimePattern;
1630                                 break;
1631                         case 'g':
1632                                 pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
1633                                 break;
1634                         case 'G':
1635                                 pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
1636                                 break;
1637                         case 'm':
1638                         case 'M':
1639                                 pattern = dfi.MonthDayPattern;
1640                                 break;
1641                         case 'r':
1642                         case 'R':
1643                                 pattern = dfi.RFC1123Pattern;
1644                                 // commented by LP 09/jun/2002, rfc 1123 pattern is always in GMT
1645                                 // uncommented by AE 27/may/2004
1646 //                              useutc = true;
1647                                 use_invariant = true;
1648                                 break;
1649                         case 's':
1650                                 pattern = dfi.SortableDateTimePattern;
1651                                 break;
1652                         case 't':
1653                                 pattern = dfi.ShortTimePattern;
1654                                 break;
1655                         case 'T':
1656                                 pattern = dfi.LongTimePattern;
1657                                 break;
1658                         case 'u':
1659                                 pattern = dfi.UniversalSortableDateTimePattern;
1660                                 useutc = true;
1661                                 break;
1662                         case 'U':
1663 //                              pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
1664                                 pattern = dfi.FullDateTimePattern;
1665                                 useutc = true;
1666                                 break;
1667                         case 'y':
1668                         case 'Y':
1669                                 pattern = dfi.YearMonthPattern;
1670                                 break;
1671                         default:
1672                                 pattern = null;
1673                                 break;
1674                         }
1675
1676                         return pattern;
1677                 }
1678
1679                 internal string _ToString (string format, DateTimeFormatInfo dfi)
1680                 {
1681                         // the length of the format is usually a good guess of the number
1682                         // of chars in the result. Might save us a few bytes sometimes
1683                         // Add + 10 for cases like mmmm dddd
1684                         StringBuilder result = new StringBuilder (format.Length + 10);
1685
1686                         // For some cases, the output should not use culture dependent calendar
1687                         DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo;
1688                         if (format == inv.RFC1123Pattern)
1689                                 dfi = inv;
1690                         else if (format == inv.UniversalSortableDateTimePattern)
1691                                 dfi = inv;
1692
1693                         int i = 0;
1694
1695                         while (i < format.Length) {
1696                                 int tokLen;
1697                                 char ch = format [i];
1698
1699                                 switch (ch) {
1700
1701                                 //
1702                                 // Time Formats
1703                                 //
1704                                 case 'h':
1705                                         // hour, [1, 12]
1706                                         tokLen = CountRepeat (format, i, ch);
1707
1708                                         int hr = this.Hour % 12;
1709                                         if (hr == 0)
1710                                                 hr = 12;
1711
1712                                         ZeroPad (result, hr, tokLen == 1 ? 1 : 2);
1713                                         break;
1714                                 case 'H':
1715                                         // hour, [0, 23]
1716                                         tokLen = CountRepeat (format, i, ch);
1717                                         ZeroPad (result, this.Hour, tokLen == 1 ? 1 : 2);
1718                                         break;
1719                                 case 'm':
1720                                         // minute, [0, 59]
1721                                         tokLen = CountRepeat (format, i, ch);
1722                                         ZeroPad (result, this.Minute, tokLen == 1 ? 1 : 2);
1723                                         break;
1724                                 case 's':
1725                                         // second [0, 29]
1726                                         tokLen = CountRepeat (format, i, ch);
1727                                         ZeroPad (result, this.Second, tokLen == 1 ? 1 : 2);
1728                                         break;
1729                                 case 'f':
1730                                         // fraction of second, to same number of
1731                                         // digits as there are f's
1732
1733                                         tokLen = CountRepeat (format, i, ch);
1734                                         if (tokLen > 7)
1735                                                 throw new FormatException ("Invalid Format String");
1736
1737                                         int dec = (int)((long)(this.Ticks % TimeSpan.TicksPerSecond) / (long) Math.Pow (10, 7 - tokLen));
1738                                         ZeroPad (result, dec, tokLen);
1739
1740                                         break;
1741                                 case 't':
1742                                         // AM/PM. t == first char, tt+ == full
1743                                         tokLen = CountRepeat (format, i, ch);
1744                                         string desig = this.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator;
1745
1746                                         if (tokLen == 1) {
1747                                                 if (desig.Length >= 1)
1748                                                         result.Append (desig [0]);
1749                                         }
1750                                         else
1751                                                 result.Append (desig);
1752
1753                                         break;
1754                                 case 'z':
1755                                         // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm
1756                                         tokLen = CountRepeat (format, i, ch);
1757                                         TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset (this);
1758
1759                                         if (offset.Ticks >= 0)
1760                                                 result.Append ('+');
1761                                         else
1762                                                 result.Append ('-');
1763
1764                                         switch (tokLen) {
1765                                         case 1:
1766                                                 result.Append (Math.Abs (offset.Hours));
1767                                                 break;
1768                                         case 2:
1769                                                 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1770                                                 break;
1771                                         default:
1772                                                 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1773                                                 result.Append (':');
1774                                                 result.Append (Math.Abs (offset.Minutes).ToString ("00"));
1775                                                 break;
1776                                         }
1777                                         break;
1778                                 //
1779                                 // Date tokens
1780                                 //
1781                                 case 'd':
1782                                         // day. d(d?) = day of month (leading 0 if two d's)
1783                                         // ddd = three leter day of week
1784                                         // dddd+ full day-of-week
1785                                         tokLen = CountRepeat (format, i, ch);
1786
1787                                         if (tokLen <= 2)
1788                                                 ZeroPad (result, dfi.Calendar.GetDayOfMonth (this), tokLen == 1 ? 1 : 2);
1789                                         else if (tokLen == 3)
1790                                                 result.Append (dfi.GetAbbreviatedDayName (dfi.Calendar.GetDayOfWeek (this)));
1791                                         else
1792                                                 result.Append (dfi.GetDayName (dfi.Calendar.GetDayOfWeek (this)));
1793
1794                                         break;
1795                                 case 'M':
1796                                         // Month.m(m?) = month # (with leading 0 if two mm)
1797                                         // mmm = 3 letter name
1798                                         // mmmm+ = full name
1799                                         tokLen = CountRepeat (format, i, ch);
1800                                         int month = dfi.Calendar.GetMonth(this);
1801                                         if (tokLen <= 2)
1802                                                 ZeroPad (result, month, tokLen);
1803                                         else if (tokLen == 3)
1804                                                 result.Append (dfi.GetAbbreviatedMonthName (month));
1805                                         else
1806                                                 result.Append (dfi.GetMonthName (month));
1807
1808                                         break;
1809                                 case 'y':
1810                                         // Year. y(y?) = two digit year, with leading 0 if yy
1811                                         // yyy+ full year, if yyy and yr < 1000, displayed as three digits
1812                                         tokLen = CountRepeat (format, i, ch);
1813
1814                                         if (tokLen <= 2)
1815                                                 ZeroPad (result, dfi.Calendar.GetYear (this) % 100, tokLen);
1816                                         else
1817                                                 ZeroPad (result, dfi.Calendar.GetYear (this), (tokLen == 3 ? 3 : 4));
1818
1819                                         break;
1820                                 case 'g':
1821                                         // Era name
1822                                         tokLen = CountRepeat (format, i, ch);
1823                                         result.Append (dfi.GetEraName (dfi.Calendar.GetEra (this)));
1824                                         break;
1825
1826                                 //
1827                                 // Other
1828                                 //
1829                                 case ':':
1830                                         result.Append (dfi.TimeSeparator);
1831                                         tokLen = 1;
1832                                         break;
1833                                 case '/':
1834                                         result.Append (dfi.DateSeparator);
1835                                         tokLen = 1;
1836                                         break;
1837                                 case '\'': case '"':
1838                                         tokLen = ParseQuotedString (format, i, result);
1839                                         break;
1840                                 case '%':
1841                                         if (i >= format.Length - 1)
1842                                                 throw new FormatException ("% at end of date time string");
1843                                         if (format [i + 1] == '%')
1844                                                 throw new FormatException ("%% in date string");
1845
1846                                         // Look for the next char
1847                                         tokLen = 1;
1848                                         break;
1849                                 case '\\':
1850                                         // C-Style escape
1851                                         if (i >= format.Length - 1)
1852                                                 throw new FormatException ("\\ at end of date time string");
1853
1854                                         result.Append (format [i + 1]);
1855                                         tokLen = 2;
1856
1857                                         break;
1858                                 default:
1859                                         // catch all
1860                                         result.Append (ch);
1861                                         tokLen = 1;
1862                                         break;
1863                                 }
1864                                 i += tokLen;
1865                         }
1866                         return result.ToString ();
1867                 }
1868                 
1869                 static int CountRepeat (string fmt, int p, char c)
1870                 {
1871                         int l = fmt.Length;
1872                         int i = p + 1;
1873                         while ((i < l) && (fmt [i] == c)) 
1874                                 i++;
1875                         
1876                         return i - p;
1877                 }
1878                 
1879                 static int ParseQuotedString (string fmt, int pos, StringBuilder output)
1880                 {
1881                         // pos == position of " or '
1882                         
1883                         int len = fmt.Length;
1884                         int start = pos;
1885                         char quoteChar = fmt [pos++];
1886                         
1887                         while (pos < len) {
1888                                 char ch = fmt [pos++];
1889                                 
1890                                 if (ch == quoteChar)
1891                                         return pos - start;
1892                                 
1893                                 if (ch == '\\') {
1894                                         // C-Style escape
1895                                         if (pos >= len)
1896                                                 throw new FormatException("Un-ended quote");
1897         
1898                                         output.Append (fmt [pos++]);
1899                                 } else {
1900                                         output.Append (ch);
1901                                 }
1902                         }
1903
1904                         throw new FormatException("Un-ended quote");
1905                 }
1906                 
1907                 static unsafe void ZeroPad (StringBuilder output, int digits, int len)
1908                 {
1909                         // more than enough for an int
1910                         char* buffer = stackalloc char [16];
1911                         int pos = 16;
1912                         
1913                         do {
1914                                 buffer [-- pos] = (char) ('0' + digits % 10);
1915                                 digits /= 10;
1916                                 len --;
1917                         } while (digits > 0);
1918                         
1919                         while (len -- > 0)
1920                                 buffer [-- pos] = '0';
1921                         
1922                         output.Append (new string (buffer, pos, 16 - pos));
1923                 }
1924
1925                 public string ToString (string format, IFormatProvider fp)
1926
1927                 {
1928                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance(fp);
1929
1930                         if (format == null)
1931                                 format = "G";
1932
1933                         bool useutc = false, use_invariant = false;
1934
1935                         if (format.Length == 1) {
1936                                 char fchar = format [0];
1937                                 format = _GetStandardPattern (fchar, dfi, out useutc, out use_invariant);
1938                         }
1939
1940                         // Don't convert UTC value. It just adds 'Z' for 
1941                         // 'u' format, for the same ticks.
1942                         return this._ToString (format, dfi);
1943                 }
1944
1945                 public DateTime ToLocalTime ()
1946                 {
1947                         return TimeZone.CurrentTimeZone.ToLocalTime (this);
1948                 }
1949
1950                 public DateTime ToUniversalTime()
1951                 {
1952                         return TimeZone.CurrentTimeZone.ToUniversalTime (this);
1953                 }
1954
1955                 /*  OPERATORS */
1956
1957                 public static DateTime operator +(DateTime d, TimeSpan t)
1958                 {
1959                         return new DateTime (true, d.ticks + t);
1960                 }
1961
1962                 public static bool operator ==(DateTime d1, DateTime d2)
1963                 {
1964                         return (d1.ticks == d2.ticks);
1965                 }
1966
1967                 public static bool operator >(DateTime t1,DateTime t2)
1968                 {
1969                         return (t1.ticks > t2.ticks);
1970                 }
1971
1972                 public static bool operator >=(DateTime t1,DateTime t2)
1973                 {
1974                         return (t1.ticks >= t2.ticks);
1975                 }
1976
1977                 public static bool operator !=(DateTime d1, DateTime d2)
1978                 {
1979                         return (d1.ticks != d2.ticks);
1980                 }
1981
1982                 public static bool operator <(DateTime t1,      DateTime t2)
1983                 {
1984                         return (t1.ticks < t2.ticks );
1985                 }
1986
1987                 public static bool operator <=(DateTime t1,DateTime t2)
1988                 {
1989                         return (t1.ticks <= t2.ticks);
1990                 }
1991
1992                 public static TimeSpan operator -(DateTime d1,DateTime d2)
1993                 {
1994                         return new TimeSpan((d1.ticks - d2.ticks).Ticks);
1995                 }
1996
1997                 public static DateTime operator -(DateTime d,TimeSpan t)
1998                 {
1999                         return new DateTime (true, d.ticks - t);
2000                 }
2001
2002                 bool IConvertible.ToBoolean(IFormatProvider provider)
2003                 {
2004                         throw new InvalidCastException();
2005                 }
2006                 
2007                 byte IConvertible.ToByte(IFormatProvider provider)
2008                 {
2009                         throw new InvalidCastException();
2010
2011                 }
2012
2013                 char IConvertible.ToChar(IFormatProvider provider)
2014                 {
2015                         throw new InvalidCastException();
2016                 }
2017
2018                 System.DateTime IConvertible.ToDateTime(IFormatProvider provider)
2019                 {
2020                         return this;
2021                 } 
2022                 
2023                 decimal IConvertible.ToDecimal(IFormatProvider provider)
2024                 {
2025                          throw new InvalidCastException();
2026                 }
2027
2028                 double IConvertible.ToDouble(IFormatProvider provider)
2029                 {
2030                         throw new InvalidCastException();
2031                 }
2032
2033                 Int16 IConvertible.ToInt16(IFormatProvider provider)
2034                 {
2035                         throw new InvalidCastException();
2036                 }
2037
2038                 Int32 IConvertible.ToInt32(IFormatProvider provider)
2039                 {
2040                         throw new InvalidCastException();
2041                 }
2042
2043                 Int64 IConvertible.ToInt64(IFormatProvider provider)
2044                 {
2045                         throw new InvalidCastException();
2046                 }
2047
2048                 SByte IConvertible.ToSByte(IFormatProvider provider)
2049                 {
2050                         throw new InvalidCastException();
2051                 }
2052
2053                 Single IConvertible.ToSingle(IFormatProvider provider)
2054                 {
2055                         throw new InvalidCastException();
2056                 }
2057
2058                 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
2059                 {
2060                         if (conversionType == null)
2061                                 throw new ArgumentNullException ("conversionType");
2062
2063                         if (conversionType == typeof (DateTime))
2064                                 return this;
2065                         else if (conversionType == typeof (String))
2066                                 return this.ToString (provider);
2067                         else if (conversionType == typeof (Object))
2068                                 return this;
2069                         else
2070                                 throw new InvalidCastException();
2071                 }
2072
2073                 UInt16 IConvertible.ToUInt16(IFormatProvider provider)
2074                 {
2075                         throw new InvalidCastException();
2076                 }
2077                 
2078                 UInt32 IConvertible.ToUInt32(IFormatProvider provider)
2079                 {
2080                         throw new InvalidCastException();
2081                 }
2082
2083                 UInt64 IConvertible.ToUInt64(IFormatProvider provider)
2084                 {
2085                         throw new InvalidCastException();
2086                 }
2087         }
2088 }