2008-09-15 Andy Hume <andyhume32@yahoo.co.uk>
[mono.git] / mcs / class / corlib / System / DateTimeOffset.cs
1 /*
2  * System.DateTimeOffset.cs
3  *
4  * Author(s)
5  *      Stephane Delcroix <stephane@delcroix.org>
6  *      Marek Safar (marek.safar@gmail.com)
7  *
8  *  Copyright (C) 2007 Novell, Inc (http://www.novell.com) 
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining
11  * a copy of this software and associated documentation files (the
12  * "Software"), to deal in the Software without restriction, including
13  * without limitation the rights to use, copy, modify, merge, publish,
14  * distribute, sublicense, and/or sell copies of the Software, and to
15  * permit persons to whom the Software is furnished to do so, subject to
16  * the following conditions:
17  * 
18  * The above copyright notice and this permission notice shall be
19  * included in all copies or substantial portions of the Software.
20  * 
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28  */
29
30
31 #if NET_2_0 // Introduced by .NET 3.5 for 2.0 mscorlib
32
33 using System.Globalization;
34 using System.Runtime.InteropServices;
35 using System.Runtime.Serialization;
36 using System.Text;
37
38 namespace System
39 {
40         [Serializable]
41         [StructLayout (LayoutKind.Auto)]
42         public struct DateTimeOffset : IComparable, IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>
43         {
44                 public static readonly DateTimeOffset MaxValue = new DateTimeOffset (DateTime.MaxValue, TimeSpan.Zero);
45                 public static readonly DateTimeOffset MinValue = new DateTimeOffset (DateTime.MinValue, TimeSpan.Zero);
46                 
47                 DateTime dt;
48                 TimeSpan utc_offset;
49         
50                 public DateTimeOffset (DateTime dateTime)
51                 {
52                         dt = dateTime;
53
54                         if (dateTime.Kind == DateTimeKind.Utc)
55                                 utc_offset = TimeSpan.Zero;
56                         else 
57                                 utc_offset = TimeZone.CurrentTimeZone.GetUtcOffset (dateTime);
58                                 
59                         if (UtcDateTime < DateTime.MinValue || UtcDateTime > DateTime.MaxValue)
60                                 throw new ArgumentOutOfRangeException ("The UTC date and time that results from applying the offset is earlier than MinValue or later than MaxValue.");
61
62                 }
63                 
64                 public DateTimeOffset (DateTime dateTime, TimeSpan offset)
65                 {
66                         if (dateTime.Kind == DateTimeKind.Utc && offset != TimeSpan.Zero)
67                                 throw new ArgumentException ("dateTime.Kind equals Utc and offset does not equal zero.");
68
69                         if (dateTime.Kind == DateTimeKind.Local && offset != TimeZone.CurrentTimeZone.GetUtcOffset (dateTime))
70                                 throw new ArgumentException ("dateTime.Kind equals Local and offset does not equal the offset of the system's local time zone.");
71
72                         if (offset.Ticks % TimeSpan.TicksPerMinute != 0)
73                                 throw new ArgumentException ("offset is not specified in whole minutes.");
74
75                         if (offset < new TimeSpan (-14, 0 ,0) || offset > new TimeSpan (14, 0, 0))
76                                 throw new ArgumentOutOfRangeException ("offset is less than -14 hours or greater than 14 hours.");
77
78                         dt = dateTime;
79                         utc_offset = offset;
80
81                         if (UtcDateTime < DateTime.MinValue || UtcDateTime > DateTime.MaxValue)
82                                 throw new ArgumentOutOfRangeException ("The UtcDateTime property is earlier than MinValue or later than MaxValue.");
83                 }
84
85                 public DateTimeOffset (long ticks, TimeSpan offset) : this (new DateTime (ticks), offset)
86                 {
87                 }
88
89                 public DateTimeOffset (int year, int month, int day, int hour, int minute, int second, TimeSpan offset) : 
90                         this (new DateTime (year, month, day, hour, minute, second), offset)
91                 {
92                 }
93
94                 public DateTimeOffset (int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) :
95                         this (new DateTime (year, month, day, hour, minute, second, millisecond), offset)
96                 {
97                 }
98
99                 public DateTimeOffset (int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) :
100                         this (new DateTime (year, month, day, hour, minute, second, millisecond, calendar), offset)
101                 {
102                 }
103
104                 public DateTimeOffset Add (TimeSpan timeSpan)
105                 {
106                         return new DateTimeOffset (dt.Add (timeSpan), utc_offset);
107                 }
108         
109                 public DateTimeOffset AddDays (double days)
110                 {
111                         return new DateTimeOffset (dt.AddDays (days), utc_offset);      
112                 }
113                 
114                 public DateTimeOffset AddHours (double hours)
115                 {
116                         return new DateTimeOffset (dt.AddHours (hours), utc_offset);
117                 }
118
119                 public static DateTimeOffset operator + (DateTimeOffset dateTimeTz, TimeSpan timeSpan)
120                 {
121                         return dateTimeTz.Add (timeSpan);
122                 }
123
124                 public DateTimeOffset AddMilliseconds (double milliseconds)
125                 {
126                         return new DateTimeOffset (dt.AddMilliseconds (milliseconds), utc_offset);
127                 }
128
129                 public DateTimeOffset AddMinutes (double minutes)
130                 {
131                         return new DateTimeOffset (dt.AddMinutes (minutes), utc_offset);        
132                 }
133
134                 public DateTimeOffset AddMonths (int months)
135                 {
136                         return new DateTimeOffset (dt.AddMonths (months), utc_offset);
137                 }
138
139                 public DateTimeOffset AddSeconds (double seconds)
140                 {
141                         return new DateTimeOffset (dt.AddSeconds (seconds), utc_offset);
142                 }
143
144                 public DateTimeOffset AddTicks (long ticks)
145                 {
146                         return new DateTimeOffset (dt.AddTicks (ticks), utc_offset);    
147                 }
148
149                 public DateTimeOffset AddYears (int years)
150                 {
151                         return new DateTimeOffset (dt.AddYears (years), utc_offset);
152                 }
153
154                 public static int Compare (DateTimeOffset first, DateTimeOffset second)
155                 {
156                         return first.CompareTo (second);        
157                 }
158
159                 public int CompareTo (DateTimeOffset other)
160                 {
161                         return UtcDateTime.CompareTo (other.UtcDateTime);
162                 }
163
164                 int IComparable.CompareTo (object obj)
165                 {
166                         return CompareTo ((DateTimeOffset) obj);
167                 }
168
169                 public static bool operator == (DateTimeOffset left, DateTimeOffset right)
170                 {
171                         return left.Equals (right);     
172                 }
173
174                 public bool Equals (DateTimeOffset other)
175                 {
176                         return UtcDateTime == other.UtcDateTime;
177                 }
178
179                 public override bool Equals (object obj)
180                 {
181                         if (obj is DateTimeOffset)
182                                 return UtcDateTime == ((DateTimeOffset) obj).UtcDateTime;
183                         return false;
184                 }
185
186                 public static bool Equals (DateTimeOffset first, DateTimeOffset second)
187                 {
188                         return first.Equals (second);   
189                 }
190
191                 public bool EqualsExact (DateTimeOffset other)
192                 {
193                         return dt == other.dt && utc_offset == other.utc_offset;        
194                 }
195
196                 public static DateTimeOffset FromFileTime (long fileTime)
197                 {
198                         if (fileTime < 0 || fileTime > MaxValue.Ticks)
199                                 throw new ArgumentOutOfRangeException ("fileTime is less than zero or greater than DateTimeOffset.MaxValue.Ticks.");
200                         
201                         return new DateTimeOffset (DateTime.FromFileTime (fileTime), TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.FromFileTime (fileTime)));
202
203                 }
204
205                 public override int GetHashCode ()
206                 {
207                         return dt.GetHashCode () ^ utc_offset.GetHashCode ();
208                 }
209
210                 [System.Security.Permissions.SecurityPermission (System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter = true)]
211                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
212                 {
213                         if (info == null)
214                                 throw new ArgumentNullException ("info");
215                         // An example SOAP serialization on MSFT is the following, so field 
216                         // names "DateTime" and "OffsetMinutes":
217                         //    <SOAP-ENV:Envelope ...>
218                         //    <SOAP-ENV:Body>
219                         //    <a1:DateTimeOffset id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/ns/System">
220                         //    <DateTime xsi:type="xsd:dateTime">2007-01-02T12:30:50.0000000+00:00</DateTime>
221                         //    <OffsetMinutes>0</OffsetMinutes>
222                         //    </a1:DateTimeOffset>
223                         //    </SOAP-ENV:Body>
224                         //    </SOAP-ENV:Envelope>
225                         DateTime dt0 = new DateTime (dt.Ticks).Subtract (utc_offset);
226                         info.AddValue ("DateTime", dt0);
227                         // MSFT BinaryFormatter output contains primitive code 6, i.e. Int16.
228                         info.AddValue ("OffsetMinutes", (Int16)utc_offset.TotalMinutes);
229                 }
230
231                 [System.Security.Permissions.SecurityPermission (System.Security.Permissions.SecurityAction.LinkDemand, SerializationFormatter = true)]
232                 private DateTimeOffset(SerializationInfo info, StreamingContext context)
233                 {
234                         DateTime dt0 = (DateTime)info.GetValue ("DateTime", typeof(DateTime));
235                         Int16 totalMinutes = info.GetInt16 ("OffsetMinutes");
236                         utc_offset = TimeSpan.FromMinutes(totalMinutes);
237                         dt = dt0.Add(utc_offset);
238                 }
239
240                 public static bool operator > (DateTimeOffset left, DateTimeOffset right)
241                 {
242                         return left.UtcDateTime > right.UtcDateTime;
243                 }                       
244
245                 public static bool operator >= (DateTimeOffset left, DateTimeOffset right)
246                 {
247                         return left.UtcDateTime >= right.UtcDateTime;
248                 }                       
249
250                 public static implicit operator DateTimeOffset (DateTime dateTime)
251                 {
252                         return new DateTimeOffset (dateTime);
253                 }
254
255                 public static bool operator != (DateTimeOffset left, DateTimeOffset right)
256                 {
257                         return left.UtcDateTime != right.UtcDateTime;
258                 }
259
260                 public static bool operator < (DateTimeOffset left, DateTimeOffset right)
261                 {
262                         return left.UtcDateTime < right.UtcDateTime;
263                 }
264                 
265                 public static bool operator <= (DateTimeOffset left, DateTimeOffset right)
266                 {
267                         return left.UtcDateTime <= right.UtcDateTime;
268                 }
269         
270                 [MonoTODO]
271                 void IDeserializationCallback.OnDeserialization (object sender)
272                 {
273                 }
274
275                 public static DateTimeOffset Parse (string input)
276                 {
277                         return Parse (input, null);
278                 }
279
280                 public static DateTimeOffset Parse (string input, IFormatProvider formatProvider)
281                 {
282                         return Parse (input, formatProvider, DateTimeStyles.AllowWhiteSpaces);
283                 }
284
285                 [MonoTODO]
286                 public static DateTimeOffset Parse (string input, IFormatProvider formatProvider, DateTimeStyles styles)
287                 {
288                         if (input == null)
289                                 throw new ArgumentNullException ("input");
290
291                         throw new NotImplementedException ();
292                 }
293
294                 public static DateTimeOffset ParseExact (string input, string format, IFormatProvider formatProvider)
295                 {
296                         return ParseExact (input, format, formatProvider, DateTimeStyles.AssumeLocal);
297                 }
298
299                 public static DateTimeOffset ParseExact (string input, string format, IFormatProvider formatProvider, DateTimeStyles styles)
300                 {
301                         if (format == null)
302                                 throw new ArgumentNullException ("format");
303
304                         if (format == String.Empty)
305                                 throw new FormatException ("format is an empty string");
306
307                         return ParseExact (input, new string [] {format}, formatProvider, styles);
308                 }
309
310                 public static DateTimeOffset ParseExact (string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles)
311                 {
312                         if (input == null)
313                                 throw new ArgumentNullException ("input");
314
315                         if (input == String.Empty)
316                                 throw new FormatException ("input is an empty string");
317
318                         if (formats == null)
319                                 throw new ArgumentNullException ("formats");
320
321                         if (formats.Length == 0)
322                                 throw new FormatException ("Invalid format specifier");
323
324                         if ((styles & DateTimeStyles.AssumeLocal) != 0 && (styles & DateTimeStyles.AssumeUniversal) != 0)
325                                 throw new ArgumentException ("styles parameter contains incompatible flags");
326
327                         DateTimeOffset result;
328                         if (!ParseExact (input, formats, DateTimeFormatInfo.GetInstance (formatProvider), styles, out result))
329                                 throw new FormatException ();
330
331                         return result;
332                 }
333
334                 private static bool ParseExact (string input, string [] formats,
335                                 DateTimeFormatInfo dfi, DateTimeStyles styles, out DateTimeOffset ret)
336                 {
337                         foreach (string format in formats)
338                         {
339                                 if (format == null || format == String.Empty)
340                                         throw new FormatException ("Invlid Format Sting");
341
342                                 DateTimeOffset result;
343                                 if (DoParse (input, format, false, out result, dfi, styles)) {
344                                         ret = result;
345                                         return true;
346                                 }
347                         }
348                         ret = DateTimeOffset.MinValue;
349                         return false;
350                 }
351
352                 private static bool DoParse (string input, 
353                                 string format,
354                                 bool exact,
355                                 out DateTimeOffset result,
356                                 DateTimeFormatInfo dfi,
357                                 DateTimeStyles styles)
358                 {
359                         if ((styles & DateTimeStyles.AllowLeadingWhite) != 0) {
360                                 format = format.TrimStart (null);
361                                 input = input.TrimStart (null);
362                         }
363
364                         if ((styles & DateTimeStyles.AllowTrailingWhite) != 0) {
365                                 format = format.TrimEnd (null);
366                                 input = input.TrimEnd (null);
367                         }
368
369                         bool allow_white_spaces = false;
370                         if ((styles & DateTimeStyles.AllowInnerWhite) != 0)
371                                 allow_white_spaces = true;
372
373                         bool useutc = false, use_invariants = false;
374                         if (format.Length == 1)
375                                 format = DateTimeUtils.GetStandardPattern (format[0], dfi, out useutc, out use_invariants, true);
376
377                         int year = -1;
378                         int month = -1;
379                         int day = -1;
380                         int partial_hour = -1; // for 'hh tt' formats
381                         int hour = -1;
382                         int minute = -1;
383                         int second = -1;
384                         double fraction = -1;
385                         int temp_int = -1;
386                         TimeSpan offset = TimeSpan.MinValue;
387
388                         result = DateTimeOffset.MinValue;
389
390                         int fi = 0; //format iterator
391                         int ii = 0; //input iterator
392                         while (fi < format.Length) {
393                                 int tokLen;
394                                 char ch = format [fi];
395
396                                 switch (ch) {
397                                 case 'd':
398                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
399                                         if (day != -1 || tokLen > 4)
400                                                 return false;
401
402                                         if (tokLen <= 2)
403                                                 ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out day);
404                                         else
405                                                 ii += ParseEnum (input, ii, tokLen == 3 ? dfi.AbbreviatedDayNames : dfi.DayNames, allow_white_spaces, out temp_int); 
406                                         break;
407                                 case 'f':
408                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
409                                         ii += ParseNumber (input, ii, tokLen, true, allow_white_spaces, out temp_int);
410                                         if (fraction >= 0 || tokLen > 7 || temp_int == -1)
411                                                 return false;
412                                         fraction = (double)temp_int / Math.Pow (10, tokLen);
413                                         break;
414                                 case 'F':
415                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
416                                         int digits;
417                                         int read = ParseNumber (input, ii, tokLen, true, allow_white_spaces, out temp_int, out digits);
418                                         if (temp_int == -1)
419                                                 ii += ParseNumber (input, ii, digits, true, allow_white_spaces, out temp_int);
420                                         else
421                                                 ii += read;
422                                         if (fraction >= 0 || tokLen > 7 || temp_int == -1)
423                                                 return false;   
424                                         fraction = (double)temp_int / Math.Pow (10, digits);    
425                                         break;
426                                 case 'h':
427                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
428                                         if (hour != -1 || tokLen > 2)
429                                                 return false;
430
431                                         ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out temp_int);
432                                         if (temp_int == -1)
433                                                 return false;
434
435                                         if (partial_hour == -1)
436                                                 partial_hour = temp_int;
437                                         else 
438                                                 hour = partial_hour + temp_int;
439                                         break;
440                                 case 'H':
441                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
442                                         if (hour != -1 || tokLen > 2)
443                                                 return false;
444
445                                         ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out hour);
446                                         break;
447                                 case 'm':
448                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
449                                         if (minute != -1 || tokLen > 2)
450                                                 return false;
451
452                                         ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out minute);
453                                         break;
454                                 case 'M':
455                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
456                                         if (month != -1 || tokLen > 4)
457                                                 return false;
458
459                                         if (tokLen <= 2)
460                                                 ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out month);
461                                         else {
462                                                 ii += ParseEnum (input, ii, tokLen == 3 ? dfi.AbbreviatedMonthNames : dfi.MonthNames, allow_white_spaces, out month);
463                                                 month += 1;
464                                         }
465
466                                         break;
467                                 case 's':
468                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
469                                         if (second != -1 || tokLen > 2)
470                                                 return false;
471                                         ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out second);
472                                         break;
473                                 case 't':
474                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
475                                         if (hour != -1 || tokLen > 2)
476                                                 return false;
477
478                                         ii += ParseEnum (input, ii,
479                                                          tokLen == 1 ? new string[] {new string (dfi.AMDesignator[0], 1), new string (dfi.PMDesignator[0], 0)} 
480                                                                      : new string[] {dfi.AMDesignator, dfi.PMDesignator},
481                                                          allow_white_spaces, out temp_int);
482                                         if (temp_int == -1)
483                                                 return false;
484
485                                         if (partial_hour == -1)
486                                                 partial_hour = temp_int * 12;
487                                         else
488                                                 hour = partial_hour + temp_int * 12;
489                                         break;
490                                 case 'y':
491                                         if (year != -1)
492                                                 return false;
493
494                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
495                                         if (tokLen <= 2) {
496                                                 ii += ParseNumber (input, ii, 2, tokLen == 2, allow_white_spaces, out year);
497                                                 if (year != -1)
498                                                         year += DateTime.Now.Year - DateTime.Now.Year % 100;
499                                         } else if (tokLen <= 4) { // yyy and yyyy accept up to 5 digits with leading 0
500                                                 int digit_parsed;
501                                                 ii += ParseNumber (input, ii, 5, false, allow_white_spaces, out year, out digit_parsed);
502                                                 if (digit_parsed < tokLen || (digit_parsed > tokLen && (year / Math.Pow (10, digit_parsed - 1) < 1)))
503                                                         return false;
504                                         } else
505                                                 ii += ParseNumber (input, ii, tokLen, true, allow_white_spaces, out year);
506                                         break;
507                                 case 'z':
508                                         tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
509                                         if (offset != TimeSpan.MinValue || tokLen > 3)
510                                                 return false;
511
512                                         int off_h, off_m = 0, sign;
513                                         temp_int = 0;
514                                         ii += ParseEnum (input, ii, new string [] {"-", "+"}, allow_white_spaces, out sign);
515                                         ii += ParseNumber (input, ii, 2, tokLen != 1, false, out off_h);
516                                         if (tokLen == 3) {
517                                                 ii += ParseEnum (input, ii, new string [] {dfi.TimeSeparator}, false, out temp_int);
518                                                 ii += ParseNumber (input, ii, 2, true, false, out off_m);
519                                         }
520                                         if (off_h == -1 || off_m == -1 || sign == -1 || temp_int == -1)
521                                                 return false;
522
523                                         if (sign == 0)
524                                                 sign = -1;
525                                         offset = new TimeSpan (sign * off_h, sign * off_m, 0);
526                                         break;
527                                 case ':':
528                                         tokLen = 1;
529                                         ii += ParseEnum (input, ii, new string [] {dfi.TimeSeparator}, false, out temp_int);
530                                         if (temp_int == -1)
531                                                 return false;
532                                         break;
533                                 case '/':
534                                         tokLen = 1;
535                                         ii += ParseEnum (input, ii, new string [] {dfi.DateSeparator}, false, out temp_int);
536                                         if (temp_int == -1)
537                                                 return false;
538                                         break;
539                                 case '%':
540                                         tokLen = 1;
541                                         if (fi != 0) 
542                                                 return false;
543                                         break;
544                                 case ' ':
545                                         tokLen = 1;
546                                         ii += ParseChar (input, ii, ' ', false, out temp_int);
547                                         if (temp_int == -1)
548                                                 return false;
549                                         break;
550                                 case '\\':
551                                         tokLen = 2;
552                                         ii += ParseChar (input, ii, format [fi + 1], allow_white_spaces, out temp_int);
553                                         if (temp_int == -1)
554                                                 return false;
555                                         break;
556                                 default:
557                                         //Console.WriteLine ("un-parsed character: {0}", ch);
558                                         tokLen = 1;
559                                         ii += ParseChar (input, ii, format [fi], allow_white_spaces, out temp_int);
560                                         if (temp_int == -1)
561                                                 return false;
562                                         break;
563                                 }
564                                 fi += tokLen;
565                         }
566
567                         //Console.WriteLine ("{0}-{1}-{2} {3}:{4} {5}", year, month, day, hour, minute, offset);
568                         if (offset == TimeSpan.MinValue && (styles & DateTimeStyles.AssumeLocal) != 0)
569                                 offset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now);
570
571                         if (offset == TimeSpan.MinValue && (styles & DateTimeStyles.AssumeUniversal) != 0)
572                                 offset = TimeSpan.Zero;
573
574                         if (hour < 0)           hour = 0;
575                         if (minute < 0)         minute = 0;
576                         if (second < 0)         second = 0;
577                         if (fraction < 0)       fraction = 0;
578                         if (year > 0 && month > 0 && day > 0) {
579                                 result = new DateTimeOffset (year, month, day, hour, minute, second, (int) (1000 * fraction), offset);
580                                 if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
581                                         result = result.ToUniversalTime ();
582                                 return true;
583                         }
584
585                         return false;
586                 }
587
588                 private static int ParseNumber (string input, int pos, int digits, bool leading_zero, bool allow_leading_white, out int result)
589                 {
590                         int digit_parsed;
591                         return ParseNumber (input, pos, digits, leading_zero, allow_leading_white, out result, out digit_parsed);
592                 }
593
594                 private static int ParseNumber (string input, int pos, int digits, bool leading_zero, bool allow_leading_white, out int result, out int digit_parsed)
595                 {
596                         int char_parsed = 0;
597                         digit_parsed = 0;
598                         result = 0;
599                         for (; allow_leading_white && pos < input.Length && input[pos] == ' '; pos++)
600                                 char_parsed++;
601
602                         for (; pos < input.Length && Char.IsDigit (input[pos]) && digits > 0; pos ++, char_parsed++, digit_parsed++, digits --)
603                                 result = 10 * result + (byte) (input[pos] - '0');
604
605                         if (leading_zero && digits > 0)
606                                 result = -1;
607
608                         if (digit_parsed == 0)
609                                 result = -1;
610
611                         return char_parsed;
612                 }
613
614                 private static int ParseEnum (string input, int pos, string [] enums, bool allow_leading_white, out int result)
615                 {
616                         int char_parsed = 0;
617                         result = -1;
618                         for (; allow_leading_white && pos < input.Length && input[pos] == ' '; pos++)
619                                 char_parsed ++;
620                         
621                         for (int i = 0; i < enums.Length; i++)
622                                 if (input.Substring(pos).StartsWith (enums [i])) {
623                                         result = i;
624                                         break;
625                                 }
626
627                         if (result >= 0)
628                                 char_parsed += enums[result].Length;
629
630                         return char_parsed;     
631                 }
632         
633                 private static int ParseChar (string input, int pos, char c, bool allow_leading_white, out int result)
634                 {
635                         int char_parsed = 0;
636                         result = -1;
637                         for (; allow_leading_white && pos < input.Length && input[pos] == ' '; pos++, char_parsed++)
638                                 ;
639
640                         if (pos < input.Length && input[pos] == c){
641                                 result = (int) c;
642                                 char_parsed ++;
643                         }
644
645                         return char_parsed;
646                 }
647
648                 public TimeSpan Subtract (DateTimeOffset value)
649                 {
650                         return UtcDateTime - value.UtcDateTime;
651                 }
652
653                 public DateTimeOffset Subtract (TimeSpan value)
654                 {
655                         return Add (-value);
656                 }
657
658                 public static TimeSpan operator - (DateTimeOffset left, DateTimeOffset right)
659                 {
660                         return left.Subtract (right);
661                 }
662
663                 public static DateTimeOffset operator - (DateTimeOffset dateTimeTz, TimeSpan timeSpan)
664                 {
665                         return dateTimeTz.Subtract (timeSpan);  
666                 }
667
668                 public long ToFileTime ()
669                 {
670                         return UtcDateTime.ToFileTime ();
671                 }
672
673                 public DateTimeOffset ToLocalTime ()
674                 {
675                         return new DateTimeOffset (UtcDateTime.ToLocalTime (), TimeZone.CurrentTimeZone.GetUtcOffset (UtcDateTime.ToLocalTime ()));
676                 }
677
678                 public DateTimeOffset ToOffset (TimeSpan offset)
679                 {
680                         return new DateTimeOffset (dt - utc_offset + offset, offset);
681                 }
682
683                 public override string ToString ()
684                 {
685                         return ToString (null, null);
686                 }
687
688                 public string ToString (IFormatProvider formatProvider)
689                 {
690                         return ToString (null, formatProvider);
691                 }
692
693                 public string ToString (string format)
694                 {
695                         return ToString (format, null);
696                 }
697
698                 public string ToString (string format, IFormatProvider formatProvider)
699                 {
700                         DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance(formatProvider);
701
702                         if (format == null || format == String.Empty)
703                                 format = dfi.ShortDatePattern + " " + dfi.LongTimePattern + " zzz";
704
705                         bool to_utc = false, use_invariant = false;
706                         if (format.Length == 1) {
707                                 char fchar = format [0];
708                                 try {
709                                         format = DateTimeUtils.GetStandardPattern (fchar, dfi, out to_utc, out use_invariant, true);
710                                 } catch {
711                                         format = null;
712                                 }
713                 
714                                 if (format == null)
715                                         throw new FormatException ("format is not one of the format specifier characters defined for DateTimeFormatInfo");
716                         }
717                         return to_utc ? DateTimeUtils.ToString (UtcDateTime, TimeSpan.Zero, format, dfi) : DateTimeUtils.ToString (DateTime, Offset, format, dfi);
718                 }
719
720                 public DateTimeOffset ToUniversalTime ()
721                 {
722                         return new DateTimeOffset (UtcDateTime, TimeSpan.Zero); 
723                 }
724
725                 public static bool TryParse (string input, out DateTimeOffset result)
726                 {
727                         try {
728                                 result = Parse (input);
729                                 return true;
730                         } catch {
731                                 result = MinValue;
732                                 return false;
733                         }
734                 }
735
736                 public static bool TryParse (string input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
737                 {
738                         try {
739                                 result = Parse (input, formatProvider, styles);
740                                 return true;
741                         } catch {
742                                 result = MinValue;
743                                 return false;
744                         }       
745                 }
746
747                 public static bool TryParseExact (string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
748                 {
749                         try {
750                                 result = ParseExact (input, format, formatProvider, styles);
751                                 return true;
752                         } catch {
753                                 result = MinValue;
754                                 return false;
755                         }
756                 }
757
758                 public static bool TryParseExact (string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result)
759                 {
760                         try {
761                                 result = ParseExact (input, formats, formatProvider, styles);
762                                 return true;
763                         } catch {
764                                 result = MinValue;
765                                 return false;
766                         }
767                 }
768
769                 public DateTime Date {
770                         get { return DateTime.SpecifyKind (dt.Date, DateTimeKind.Unspecified); }
771                 }
772
773                 public DateTime DateTime {
774                         get { return DateTime.SpecifyKind (dt, DateTimeKind.Unspecified); }
775                 }
776
777                 public int Day {
778                         get { return dt.Day; }
779                 }
780
781                 public DayOfWeek DayOfWeek {
782                         get { return dt.DayOfWeek; }
783                 }
784
785                 public int DayOfYear {
786                         get { return dt.DayOfYear; }
787                 }
788
789                 public int Hour {
790                         get { return dt.Hour; }
791                 }
792
793                 public DateTime LocalDateTime {
794                         get { return UtcDateTime.ToLocalTime (); }
795                 }
796
797                 public int Millisecond {
798                         get { return dt.Millisecond; }
799                 }
800
801                 public int Minute {
802                         get { return dt.Minute; }
803                 }
804
805                 public int Month {
806                         get { return dt.Month; }
807                 }
808
809                 public static DateTimeOffset Now {
810                         get { return new DateTimeOffset (DateTime.Now);}
811                 }
812
813                 public TimeSpan Offset {
814                         get { return utc_offset; }      
815                 }
816
817                 public int Second {
818                         get { return dt.Second; }
819                 }
820
821                 public long Ticks {
822                         get { return dt.Ticks; }        
823                 }
824
825                 public TimeSpan TimeOfDay {
826                         get { return dt.TimeOfDay; }
827                 }
828
829                 public DateTime UtcDateTime {
830                         get { return DateTime.SpecifyKind (dt - utc_offset, DateTimeKind.Utc); }        
831                 }
832                 
833                 public static DateTimeOffset UtcNow {
834                         get { return new DateTimeOffset (DateTime.UtcNow); }
835                 }
836
837                 public long UtcTicks {
838                         get { return UtcDateTime.Ticks; }
839                 }
840
841                 public int Year {
842                         get { return dt.Year; }
843                 }
844         }
845 }
846 #endif