5 // Marcel Narings (marcel@narings.nl)
6 // Martin Baulig (martin@gnome.org)
7 // Atsushi Enomoto (atsushi@ximian.com)
9 // (C) 2001 Marcel Narings
10 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
33 using System.Globalization;
34 using System.Runtime.CompilerServices;
35 using System.Runtime.InteropServices;
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.
46 [StructLayout (LayoutKind.Auto)]
47 public struct DateTime : IFormattable, IConvertible, IComparable
49 , IComparable<DateTime>, IEquatable <DateTime>
52 private TimeSpan ticks;
58 private const int dp400 = 146097;
59 private const int dp100 = 36524;
60 private const int dp4 = 1461;
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;
66 //private const long MAX_VALUE_TICKS = 3155378975400000000L;
67 // -- Microsoft .NET has this value.
68 private const long MAX_VALUE_TICKS = 3155378975999999999L;
71 // The UnixEpoch, it begins on Jan 1, 1970 at 0:0:0, expressed
74 internal const long UnixEpoch = 621355968000000000L;
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;
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));
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
90 // Note that those format should be tried only for
93 // FIXME: SOME OF those patterns looks tried against
94 // the current culture, since some patterns fail in
98 "yyyy-MM-ddTHH:mm:sszzz",
99 "yyyy-MM-ddTHH:mm:ss.fffffff",
100 "yyyy-MM-ddTHH:mm:ss.fffffffzzz",
102 "yyyy-M-d H:m:s.fffffff",
103 // UTC / allow any separator
104 "yyyy/MM/ddTHH:mm:ssZ",
109 "yyyy/MM/dd HH:mm:ss 'GMT'",
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",
119 "M/d/yyyy HH':'mm':'ss tt",
121 // another funky COM dependent one
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",
131 // DayOfTheWeek, dd yyyy. This works for every locales.
134 // X509Certificate pattern is accepted by Parse() *in every culture*
137 // In Parse() the 'r' equivalent pattern is first parsed as universal time
138 "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
140 // Additionally there seems language-specific format
141 // patterns that however works in all language
143 // For example, the pattern below is for Japanese.
144 "yyyy'\u5E74'MM'\u6708'dd'\u65E5' HH'\u6642'mm'\u5206'ss'\u79D2'",
147 // Full date and time
148 "F", "G", "r", "s", "u", "U",
149 // Full date and time, but no seconds
155 // Only date, but no year
157 // Only date, but no day
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 };
173 private static int AbsoluteDays (int year, int month, int day)
178 days = (IsLeapYear(year) ? daysmonthleap : daysmonth);
182 return ((day-1) + temp + (365* (year-1)) + ((year-1)/4) - ((year-1)/100) + ((year-1)/400));
185 private int FromTicks(Which what)
187 int num400, num100, num4, numyears;
190 int[] days = daysmonth;
191 int totaldays = this.ticks.Days;
193 num400 = (totaldays / dp400);
194 totaldays -= num400 * dp400;
196 num100 = (totaldays / dp100);
197 if (num100 == 4) // leap
199 totaldays -= (num100 * dp100);
201 num4 = totaldays / dp4;
202 totaldays -= (num4 * dp4);
204 numyears = totaldays / 365 ;
206 if (numyears == 4) //leap
208 if (what == Which.Year )
209 return num400*400 + num100*100 + num4*4 + numyears + 1;
211 totaldays -= (numyears * 365) ;
212 if (what == Which.DayYear )
213 return totaldays + 1;
215 if ((numyears==3) && ((num100 == 3) || !(num4 == 24)) ) //31 dec leapyear
216 days = daysmonthleap;
218 while (totaldays >= days[M])
219 totaldays -= days[M++];
221 if (what == Which.Month )
231 /// Constructs a DateTime for specified ticks
234 public DateTime (long ticks)
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);
243 kind = DateTimeKind.Unspecified;
247 public DateTime (int year, int month, int day)
248 : this (year, month, day,0,0,0,0) {}
250 public DateTime (int year, int month, int day, int hour, int minute, int second)
251 : this (year, month, day, hour, minute, second, 0) {}
253 public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond)
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.");
265 ticks = new TimeSpan (AbsoluteDays(year,month,day), hour, minute, second, millisecond);
268 kind = DateTimeKind.Unspecified;
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)
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)
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)
288 if (calendar == null)
289 throw new ArgumentNullException ("calendar");
292 internal DateTime (bool check, TimeSpan value)
294 if (check && (value.Ticks < MinValue.Ticks || value.Ticks > MaxValue.Ticks))
295 throw new ArgumentOutOfRangeException ();
300 kind = DateTimeKind.Unspecified;
305 public DateTime (long ticks, DateTimeKind kind) : this (ticks)
307 CheckDateTimeKind (kind);
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)
314 CheckDateTimeKind (kind);
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)
321 CheckDateTimeKind (kind);
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)
328 CheckDateTimeKind (kind);
339 DateTime ret = new DateTime (Year, Month, Day);
351 return FromTicks(Which.Month);
360 return FromTicks(Which.Day);
364 public DayOfWeek DayOfWeek
368 return ( (DayOfWeek) ((ticks.Days+1) % 7) );
376 return FromTicks(Which.DayYear);
380 public TimeSpan TimeOfDay
384 return new TimeSpan(ticks.Ticks % TimeSpan.TicksPerDay );
401 return ticks.Minutes;
409 return ticks.Seconds;
413 public int Millisecond
417 return ticks.Milliseconds;
421 [MethodImplAttribute(MethodImplOptions.InternalCall)]
422 internal static extern long GetNow ();
425 // To reduce the time consumed by DateTime.Now, we keep
426 // the difference to map the system time into a local
427 // time into `to_local_time_span', we record the timestamp
428 // for this in `last_now'
430 static object to_local_time_span_object;
431 static long last_now;
433 public static DateTime Now
437 long now = GetNow ();
438 DateTime dt = new DateTime (now);
440 if ((now - last_now) > TimeSpan.TicksPerMinute){
441 to_local_time_span_object = TimeZone.CurrentTimeZone.GetLocalTimeDiff (dt);
446 // This is boxed, so we avoid locking.
447 DateTime ret = dt + (TimeSpan) to_local_time_span_object;
449 ret.kind = DateTimeKind.Local;
463 public static DateTime Today
467 DateTime today = new DateTime (now.Year, now.Month, now.Day);
469 today.kind = now.kind;
475 public static DateTime UtcNow
479 return new DateTime (GetNow (), DateTimeKind.Utc);
481 return new DateTime (GetNow ());
490 return FromTicks(Which.Year);
495 public DateTimeKind Kind {
504 public DateTime Add (TimeSpan ts)
506 DateTime ret = AddTicks (ts.Ticks);
513 public DateTime AddDays (double days)
515 return AddMilliseconds (Math.Round (days * 86400000));
518 public DateTime AddTicks (long t)
520 if ((t + ticks.Ticks) > MAX_VALUE_TICKS || (t + ticks.Ticks) < 0) {
521 throw new ArgumentOutOfRangeException();
523 DateTime ret = new DateTime (t + ticks.Ticks);
530 public DateTime AddHours (double hours)
532 return AddMilliseconds (hours * 3600000);
535 public DateTime AddMilliseconds (double ms)
537 if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
538 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
539 throw new ArgumentOutOfRangeException();
541 long msticks = (long) (ms * TimeSpan.TicksPerMillisecond);
543 return AddTicks (msticks);
546 // required to match MS implementation for OADate (OLE Automation)
547 private DateTime AddRoundedMilliseconds (double ms)
549 if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
550 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
551 throw new ArgumentOutOfRangeException ();
553 long msticks = (long) (ms += ms > 0 ? 0.5 : -0.5) * TimeSpan.TicksPerMillisecond;
555 return AddTicks (msticks);
558 public DateTime AddMinutes (double minutes)
560 return AddMilliseconds (minutes * 60000);
563 public DateTime AddMonths (int months)
565 int day, month, year, maxday ;
569 month = this.Month + (months % 12);
570 year = this.Year + months/12 ;
582 maxday = DaysInMonth(year, month);
586 temp = new DateTime (year, month, day);
590 return temp.Add (this.TimeOfDay);
593 public DateTime AddSeconds (double seconds)
595 return AddMilliseconds (seconds*1000);
598 public DateTime AddYears (int years )
600 return AddMonths(years * 12);
603 public static int Compare (DateTime t1, DateTime t2)
605 if (t1.ticks < t2.ticks)
607 else if (t1.ticks > t2.ticks)
613 public int CompareTo (object v)
618 if (!(v is System.DateTime))
619 throw new ArgumentException (Locale.GetText (
620 "Value is not a System.DateTime"));
622 return Compare (this, (DateTime) v);
626 public bool IsDaylightSavingTime ()
628 if (kind == DateTimeKind.Utc)
630 return TimeZone.CurrentTimeZone.IsDaylightSavingTime (this);
633 public int CompareTo (DateTime value)
635 return Compare (this, value);
638 public bool Equals (DateTime value)
640 return value.ticks == ticks;
643 public long ToBinary ()
646 case DateTimeKind.Utc:
647 return Ticks | 0x4000000000000000;
648 case DateTimeKind.Local:
649 return (long) ((ulong)Ticks | 0x8000000000000000);
655 public static DateTime FromBinary (long dateData)
657 switch ((ulong)dateData >> 62) {
659 return new DateTime (dateData ^ 0x4000000000000000, DateTimeKind.Utc);
661 return new DateTime (dateData, DateTimeKind.Unspecified);
663 return new DateTime (((dateData << 2) >> 2), DateTimeKind.Local);
667 public static DateTime SpecifyKind (DateTime value, DateTimeKind kind)
669 return new DateTime (value.Ticks, kind);
673 public static int DaysInMonth (int year, int month)
677 if (month < 1 || month >12)
678 throw new ArgumentOutOfRangeException ();
680 days = (IsLeapYear(year) ? daysmonthleap : daysmonth);
684 public override bool Equals (object o)
686 if (!(o is System.DateTime))
689 return ((DateTime) o).ticks == ticks;
692 public static bool Equals (DateTime t1, DateTime t2 )
694 return (t1.ticks == t2.ticks );
697 public static DateTime FromFileTime (long fileTime)
700 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
702 return new DateTime (w32file_epoch + fileTime).ToLocalTime ();
706 public static DateTime FromFileTimeUtc (long fileTime)
709 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
711 return new DateTime (w32file_epoch + fileTime);
715 public static DateTime FromOADate (double d)
717 // An OLE Automation date is implemented as a floating-point number
718 // whose value is the number of days from midnight, 30 December 1899.
720 // d must be negative 657435.0 through positive 2958466.0.
721 if ((d <= OAMinValue) || (d >= OAMaxValue))
722 throw new ArgumentException ("d", "[-657435,2958466]");
724 DateTime dt = new DateTime (ticks18991230);
726 Double days = Math.Ceiling (d);
727 // integer part is the number of days (negative)
728 dt = dt.AddRoundedMilliseconds (days * 86400000);
729 // but decimals are the number of hours (in days fractions) and positive
730 Double hours = (days - d);
731 dt = dt.AddRoundedMilliseconds (hours * 86400000);
734 dt = dt.AddRoundedMilliseconds (d * 86400000);
740 public string[] GetDateTimeFormats()
742 return GetDateTimeFormats (CultureInfo.CurrentCulture);
745 public string[] GetDateTimeFormats(char format)
747 if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
748 throw new FormatException ("Invalid format character.");
749 string[] result = new string[1];
750 result[0] = this.ToString(format.ToString());
754 public string[] GetDateTimeFormats(IFormatProvider provider)
756 DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
757 // return GetDateTimeFormats (info.GetAllDateTimePatterns ());
758 ArrayList al = new ArrayList ();
759 foreach (char c in "dDgGfFmMrRstTuUyY")
760 al.AddRange (GetDateTimeFormats (c, info));
761 return al.ToArray (typeof (string)) as string [];
764 public string[] GetDateTimeFormats(char format,IFormatProvider provider )
766 if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
767 throw new FormatException ("Invalid format character.");
769 // LAMESPEC: There is NO assurance that 'U' ALWAYS
770 // euqals to 'F', but since we have to iterate all
771 // the pattern strings, we cannot just use
772 // ToString("U", provider) here. I believe that the
773 // method's behavior cannot be formalized.
774 bool adjustutc = false;
783 DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
784 return GetDateTimeFormats (adjustutc, info.GetAllRawDateTimePatterns (format), info);
787 private string [] GetDateTimeFormats (bool adjustutc, string [] patterns, DateTimeFormatInfo dfi)
789 string [] results = new string [patterns.Length];
790 DateTime val = adjustutc ? ToUniversalTime () : this;
791 for (int i = 0; i < results.Length; i++)
792 results [i] = val._ToString (patterns [i], dfi);
797 private void CheckDateTimeKind (DateTimeKind kind) {
798 if ((kind != DateTimeKind.Unspecified) && (kind != DateTimeKind.Utc) && (kind != DateTimeKind.Local))
799 throw new ArgumentException ("Invalid DateTimeKind value.", "kind");
803 public override int GetHashCode ()
805 return (int) ticks.Ticks;
808 public TypeCode GetTypeCode ()
810 return TypeCode.DateTime;
813 public static bool IsLeapYear (int year)
815 return ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
818 public static DateTime Parse (string s)
820 return Parse (s, null);
823 public static DateTime Parse (string s, IFormatProvider fp)
825 return Parse (s, fp, DateTimeStyles.AllowWhiteSpaces);
828 public static DateTime Parse (string s, IFormatProvider fp, DateTimeStyles styles)
830 // This method should try only expected patterns.
831 // Should not try extra patterns.
832 // Right now we also try InvariantCulture, but I
833 // confirmed in some cases this method rejects what
834 // InvariantCulture supports (can be checked against
835 // "th-TH" with Gregorian Calendar). So basically it
836 // should not be done.
837 // I think it should be CurrentCulture to be tested,
838 // but right now we don't support all the supported
839 // patterns for each culture, so try InvariantCulture
840 // as a quick remedy.
842 throw new ArgumentNullException (Locale.GetText ("s is null"));
846 fp = CultureInfo.CurrentCulture;
847 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
849 bool longYear = false;
851 // Try all the patterns
852 if (ParseExact (s, dfi.GetAllDateTimePatternsInternal (), dfi, styles, out result, false, ref longYear))
855 // Try common formats.
856 // if (ParseExact (s, commonFormats, dfi, styles, out result, false, ref longYear))
859 // Try common formats with invariant culture
860 if (ParseExact (s, commonFormats, DateTimeFormatInfo.InvariantInfo, styles, out result, false, ref longYear))
864 throw new ArgumentOutOfRangeException ("year",
865 "Valid values are between 1 and 9999 inclusive");
868 throw new FormatException ("String was not recognized as a valid DateTime.");
871 public static DateTime ParseExact (string s, string format, IFormatProvider fp)
873 return ParseExact (s, format, fp, DateTimeStyles.None);
876 internal static int _ParseNumber (string s, int valuePos,
890 for (i = valuePos; i < s.Length && i < digits + valuePos; i++) {
891 if (!Char.IsDigit (s[i]))
897 digits = real_digits;
899 if (digits < min_digits) {
904 if (s.Length - valuePos < digits) {
909 for (i = valuePos; i < digits + valuePos; i++) {
911 if (!Char.IsDigit (c)) {
916 number = number * 10 + (byte) (c - '0');
923 internal static int _ParseEnum (string s, int sPos, string[] values, out int num_parsed)
927 // FIXME: I know this is somehow lame code. Probably
928 // it should iterate all the enum value and return
929 // the longest match. However right now I don't see
930 // anything but "1" and "10" - "12" that might match
931 // two or more values. (They are only abbrev month
932 // names, so do reverse order search). See bug #80094.
933 for (i = values.Length - 1; i >= 0; i--) {
934 if (s.Length - sPos < values[i].Length)
936 else if (values [i].Length == 0)
938 String tmp = s.Substring (sPos, values[i].Length);
939 if (String.Compare (tmp, values[i], true) == 0) {
940 num_parsed = values[i].Length;
949 internal static bool _ParseString (string s, int sPos, int maxlength, string value, out int num_parsed)
952 maxlength = value.Length;
954 if (String.Compare (s, sPos, value, 0, maxlength, true, CultureInfo.InvariantCulture) == 0) {
955 num_parsed = maxlength;
963 private static bool _DoParse (string s, string format, bool exact,
965 DateTimeFormatInfo dfi,
966 DateTimeStyles style,
969 bool useutc = false, use_localtime = true;
970 bool use_invariant = false;
971 bool sloppy_parsing = false;
973 if (format.Length == 1)
974 format = _GetStandardPattern (format [0], dfi, out useutc, out use_invariant);
975 else if (!exact && CultureInfo.InvariantCulture.CompareInfo.IndexOf (format, "GMT", CompareOptions.Ordinal) >= 0)
978 if ((style & DateTimeStyles.AllowLeadingWhite) != 0) {
979 format = format.TrimStart (null);
981 s = s.TrimStart (null); // it could be optimized, but will make little good.
984 if ((style & DateTimeStyles.AllowTrailingWhite) != 0) {
985 format = format.TrimEnd (null);
986 s = s.TrimEnd (null); // it could be optimized, but will make little good.
990 dfi = DateTimeFormatInfo.InvariantInfo;
992 if ((style & DateTimeStyles.AllowInnerWhite) != 0)
993 sloppy_parsing = true;
995 string chars = format;
996 int len = format.Length, pos = 0, num = 0;
998 int day = -1, dayofweek = -1, month = -1, year = -1;
999 int hour = -1, minute = -1, second = -1;
1000 double fractionalSeconds = -1;
1002 int tzsign = -1, tzoffset = -1, tzoffmin = -1;
1004 result = new DateTime (0);
1005 while (pos+num < len)
1007 if (s.Length == valuePos)
1010 if (chars[pos] == '\'') {
1012 while (pos+num < len) {
1013 if (chars[pos+num] == '\'')
1016 if (valuePos == s.Length)
1018 if (s [valuePos] != chars [pos + num])
1030 } else if (chars[pos] == '"') {
1032 while (pos+num < len) {
1033 if (chars[pos+num] == '"')
1036 if (valuePos == s.Length)
1038 if (s [valuePos] != chars[pos+num])
1050 } else if (chars[pos] == '\\') {
1056 if (s [valuePos] != chars [pos])
1061 } else if (chars[pos] == '%') {
1064 } else if (Char.IsWhiteSpace (s [valuePos]) ||
1065 s [valuePos] == ',' && Char.IsWhiteSpace (chars [pos])) {
1068 if (exact && (style & DateTimeStyles.AllowInnerWhite) == 0) {
1069 if (!Char.IsWhiteSpace (chars[pos]))
1076 while (ws < s.Length) {
1077 if (Char.IsWhiteSpace (s [ws]) || s [ws] == ',')
1084 while (ws < chars.Length) {
1085 if (Char.IsWhiteSpace (chars [ws]) || chars [ws] == ',')
1094 if ((pos+num+1 < len) && (chars[pos+num+1] == chars[pos+num])) {
1108 day = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1110 day = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1112 dayofweek = _ParseEnum (s, valuePos, dfi.RawAbbreviatedDayNames, out num_parsed);
1115 dayofweek = _ParseEnum (s, valuePos, dfi.RawDayNames, out num_parsed);
1123 month = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1125 month = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1127 month = _ParseEnum (s, valuePos, dfi.RawAbbreviatedMonthNames , out num_parsed) + 1;
1130 month = _ParseEnum (s, valuePos, dfi.RawMonthNames, out num_parsed) + 1;
1139 year = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1140 } else if (num < 3) {
1141 year = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1143 year = _ParseNumber (s, valuePos,4, 4, false, sloppy_parsing, out num_parsed);
1144 if ((year >= 1000) && (num_parsed == 4) && (!longYear) && (s.Length > 4 + valuePos)) {
1146 int ly = _ParseNumber (s, valuePos, 5, 5, false, sloppy_parsing, out np);
1147 longYear = (ly > 9999);
1152 //FIXME: We should do use dfi.Calendat.TwoDigitYearMax
1153 if (num_parsed <= 2)
1154 year += (year < 30) ? 2000 : 1900;
1160 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1163 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1174 if ((hour != -1) || (ampm >= 0))
1177 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1180 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1192 minute = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1195 minute = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1206 second = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1209 second = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1217 if (fractionalSeconds != -1)
1219 num = Math.Min (num, 6);
1220 double decimalNumber = (double) _ParseNumber (s, valuePos, 0, num+1, true, sloppy_parsing, out num_parsed);
1221 if (num_parsed == -1)
1225 fractionalSeconds = decimalNumber / Math.Pow(10.0, num_parsed);
1232 if (_ParseString (s, valuePos, 1, dfi.AMDesignator, out num_parsed))
1234 else if (_ParseString (s, valuePos, 1, dfi.PMDesignator, out num_parsed))
1241 if (_ParseString (s, valuePos, 0, dfi.AMDesignator, out num_parsed))
1243 else if (_ParseString (s, valuePos, 0, dfi.PMDesignator, out num_parsed))
1253 if (s [valuePos] == '+')
1255 else if (s [valuePos] == '-')
1261 tzoffset = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1263 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1266 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1269 valuePos += num_parsed;
1270 if (Char.IsDigit (s [valuePos]))
1272 else if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1274 valuePos += num_parsed;
1275 tzoffmin = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1282 // LAMESPEC: This should be part of UTCpattern
1283 // string and thus should not be considered here.
1285 // Note that 'Z' is not defined as a pattern
1286 // character. Keep it for X509 certificate
1287 // verification. Also, "Z" != "'Z'" under MS.NET
1288 // ("'Z'" is just literal; handled above)
1290 if (s [valuePos] != 'Z')
1298 if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1302 /* Accept any character for
1303 * DateSeparator, except
1304 * TimeSeparator, a digit or a
1305 * letter. Not documented,
1306 * but seems to be MS
1307 * behaviour here. See bug
1310 if (exact && s [valuePos] != '/')
1313 if (_ParseString (s, valuePos, 0,
1316 Char.IsDigit (s [valuePos]) ||
1317 Char.IsLetter (s [valuePos])) {
1322 if (num_parsed <= 0) {
1328 if (s [valuePos] != chars[pos]) {
1329 // FIXME: It is not sure, but
1330 // IsLetter() is introduced
1331 // because we have to reject
1332 // "2002a02b25" but have to
1333 // allow "2002$02$25". The same
1334 // thing applies to '/' case.
1336 Char.IsDigit (s [valuePos]) ||
1337 Char.IsLetter (s [valuePos]))
1348 valuePos += num_parsed;
1351 switch (chars [pos]) {
1356 if (s.Length > valuePos && s [valuePos] == 'Z'
1357 && (pos + 1 == chars.Length
1358 || chars [pos + 1] != 'Z')) {
1366 pos = pos + num + 1;
1370 // possible empty value. Regarded as no match.
1377 if (s.Length != valuePos) // extraneous tail.
1387 if (fractionalSeconds == -1)
1388 fractionalSeconds = 0;
1390 // If no date was given
1391 if ((day == -1) && (month == -1) && (year == -1)) {
1392 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
1398 month = Today.Month;
1409 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
1418 // For anything out of range
1420 if ( year < 1 || year > 9999 ||
1421 month < 1 || month >12 ||
1422 day < 1 || day > DaysInMonth(year, month) ||
1423 hour < 0 || hour > 23 ||
1424 minute < 0 || minute > 59 ||
1425 second < 0 || second > 59 )
1428 result = new DateTime (year, month, day, hour, minute, second, 0);
1429 result = result.AddSeconds(fractionalSeconds);
1431 if ((dayofweek != -1) && (dayofweek != (int) result.DayOfWeek))
1432 throw new FormatException (Locale.GetText ("String was not recognized as valid DateTime because the day of week was incorrect."));
1434 // If no timezone was specified, default to the local timezone.
1438 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1439 use_localtime = false;
1440 utcoffset = new TimeSpan (0, 0, 0);
1441 } else if (tzsign == -1) {
1442 TimeZone tz = TimeZone.CurrentTimeZone;
1443 utcoffset = tz.GetUtcOffset (result);
1445 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1446 use_localtime = false;
1453 tzoffset = -tzoffset;
1455 utcoffset = new TimeSpan (tzoffset, tzoffmin, 0);
1458 long newticks = (result.ticks - utcoffset).Ticks;
1460 result = new DateTime (false, new TimeSpan (newticks));
1462 result = result.ToLocalTime ();
1465 result.kind = DateTimeKind.Utc;
1472 public static DateTime ParseExact (string s, string format,
1473 IFormatProvider fp, DateTimeStyles style)
1477 formats = new string [1];
1478 formats[0] = format;
1480 return ParseExact (s, formats, fp, style);
1483 public static DateTime ParseExact (string s, string[] formats,
1485 DateTimeStyles style)
1487 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1490 throw new ArgumentNullException (Locale.GetText ("s is null"));
1491 if (formats == null || formats.Length == 0)
1492 throw new ArgumentNullException (Locale.GetText ("format is null"));
1495 bool longYear = false;
1496 if (!ParseExact (s, formats, dfi, style, out result, true, ref longYear))
1497 throw new FormatException ();
1502 public static bool TryParse (string s, out DateTime result)
1513 public static bool TryParse (string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
1516 result = Parse (s, provider, styles);
1524 public static bool TryParseExact (string s, string format,
1526 DateTimeStyles style,
1527 out DateTime result)
1531 formats = new string [1];
1532 formats[0] = format;
1534 return TryParseExact (s, formats, fp, style, out result);
1537 public static bool TryParseExact (string s, string[] formats,
1539 DateTimeStyles style,
1540 out DateTime result)
1542 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1544 bool longYear = false;
1545 return ParseExact (s, formats, dfi, style, out result, true, ref longYear);
1549 private static bool ParseExact (string s, string [] formats,
1550 DateTimeFormatInfo dfi, DateTimeStyles style, out DateTime ret,
1551 bool exact, ref bool longYear)
1554 for (i = 0; i < formats.Length; i++)
1558 if (_DoParse (s, formats[i], exact, out result, dfi, style, ref longYear)) {
1563 ret = DateTime.MinValue;
1567 public TimeSpan Subtract(DateTime dt)
1569 return new TimeSpan(ticks.Ticks) - dt.ticks;
1572 public DateTime Subtract(TimeSpan ts)
1576 newticks = (new TimeSpan (ticks.Ticks)) - ts;
1577 DateTime ret = new DateTime(true,newticks);
1584 public long ToFileTime()
1586 DateTime universalTime = ToUniversalTime();
1588 if (universalTime.Ticks < w32file_epoch) {
1589 throw new ArgumentOutOfRangeException("file time is not valid");
1592 return(universalTime.Ticks - w32file_epoch);
1596 public long ToFileTimeUtc()
1598 if (Ticks < w32file_epoch) {
1599 throw new ArgumentOutOfRangeException("file time is not valid");
1602 return (Ticks - w32file_epoch);
1606 public string ToLongDateString()
1608 return ToString ("D");
1611 public string ToLongTimeString()
1613 return ToString ("T");
1616 public double ToOADate ()
1618 long t = this.Ticks;
1619 // uninitialized DateTime case
1622 // we can't reach minimum value
1623 if (t < 31242239136000000)
1624 return OAMinValue + 0.001;
1626 TimeSpan ts = new TimeSpan (this.Ticks - ticks18991230);
1627 double result = ts.TotalDays;
1628 // t < 0 (where 599264352000000000 == 0.0d for OA)
1629 if (t < 599264352000000000) {
1630 // negative days (int) but decimals are positive
1631 double d = Math.Ceiling (result);
1632 result = d - 2 - (result - d);
1635 // we can't reach maximum value
1636 if (result >= OAMaxValue)
1637 result = OAMaxValue - 0.00000001d;
1642 public string ToShortDateString()
1644 return ToString ("d");
1647 public string ToShortTimeString()
1649 return ToString ("t");
1652 public override string ToString ()
1654 return ToString ("G", null);
1657 public string ToString (IFormatProvider fp)
1659 return ToString (null, fp);
1662 public string ToString (string format)
1664 return ToString (format, null);
1667 internal static string _GetStandardPattern (char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant)
1672 use_invariant = false;
1677 pattern = dfi.ShortDatePattern;
1680 pattern = dfi.LongDatePattern;
1683 pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
1686 pattern = dfi.FullDateTimePattern;
1689 pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
1692 pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
1696 pattern = dfi.MonthDayPattern;
1700 pattern = dfi.RFC1123Pattern;
1701 // commented by LP 09/jun/2002, rfc 1123 pattern is always in GMT
1702 // uncommented by AE 27/may/2004
1704 use_invariant = true;
1707 pattern = dfi.SortableDateTimePattern;
1710 pattern = dfi.ShortTimePattern;
1713 pattern = dfi.LongTimePattern;
1716 pattern = dfi.UniversalSortableDateTimePattern;
1720 // pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
1721 pattern = dfi.FullDateTimePattern;
1726 pattern = dfi.YearMonthPattern;
1736 internal string _ToString (string format, DateTimeFormatInfo dfi)
1738 // the length of the format is usually a good guess of the number
1739 // of chars in the result. Might save us a few bytes sometimes
1740 // Add + 10 for cases like mmmm dddd
1741 StringBuilder result = new StringBuilder (format.Length + 10);
1743 // For some cases, the output should not use culture dependent calendar
1744 DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo;
1745 if (format == inv.RFC1123Pattern)
1747 else if (format == inv.UniversalSortableDateTimePattern)
1752 while (i < format.Length) {
1754 char ch = format [i];
1763 tokLen = CountRepeat (format, i, ch);
1765 int hr = this.Hour % 12;
1769 ZeroPad (result, hr, tokLen == 1 ? 1 : 2);
1773 tokLen = CountRepeat (format, i, ch);
1774 ZeroPad (result, this.Hour, tokLen == 1 ? 1 : 2);
1778 tokLen = CountRepeat (format, i, ch);
1779 ZeroPad (result, this.Minute, tokLen == 1 ? 1 : 2);
1783 tokLen = CountRepeat (format, i, ch);
1784 ZeroPad (result, this.Second, tokLen == 1 ? 1 : 2);
1787 // fraction of second, to same number of
1788 // digits as there are f's
1790 tokLen = CountRepeat (format, i, ch);
1792 throw new FormatException ("Invalid Format String");
1794 int dec = (int)((long)(this.Ticks % TimeSpan.TicksPerSecond) / (long) Math.Pow (10, 7 - tokLen));
1795 ZeroPad (result, dec, tokLen);
1799 // AM/PM. t == first char, tt+ == full
1800 tokLen = CountRepeat (format, i, ch);
1801 string desig = this.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator;
1804 if (desig.Length >= 1)
1805 result.Append (desig [0]);
1808 result.Append (desig);
1812 // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm
1813 tokLen = CountRepeat (format, i, ch);
1814 TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset (this);
1816 if (offset.Ticks >= 0)
1817 result.Append ('+');
1819 result.Append ('-');
1823 result.Append (Math.Abs (offset.Hours));
1826 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1829 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1830 result.Append (':');
1831 result.Append (Math.Abs (offset.Minutes).ToString ("00"));
1839 // day. d(d?) = day of month (leading 0 if two d's)
1840 // ddd = three leter day of week
1841 // dddd+ full day-of-week
1842 tokLen = CountRepeat (format, i, ch);
1845 ZeroPad (result, dfi.Calendar.GetDayOfMonth (this), tokLen == 1 ? 1 : 2);
1846 else if (tokLen == 3)
1847 result.Append (dfi.GetAbbreviatedDayName (dfi.Calendar.GetDayOfWeek (this)));
1849 result.Append (dfi.GetDayName (dfi.Calendar.GetDayOfWeek (this)));
1853 // Month.m(m?) = month # (with leading 0 if two mm)
1854 // mmm = 3 letter name
1855 // mmmm+ = full name
1856 tokLen = CountRepeat (format, i, ch);
1857 int month = dfi.Calendar.GetMonth(this);
1859 ZeroPad (result, month, tokLen);
1860 else if (tokLen == 3)
1861 result.Append (dfi.GetAbbreviatedMonthName (month));
1863 result.Append (dfi.GetMonthName (month));
1867 // Year. y(y?) = two digit year, with leading 0 if yy
1868 // yyy+ full year, if yyy and yr < 1000, displayed as three digits
1869 tokLen = CountRepeat (format, i, ch);
1872 ZeroPad (result, dfi.Calendar.GetYear (this) % 100, tokLen);
1874 ZeroPad (result, dfi.Calendar.GetYear (this), (tokLen == 3 ? 3 : 4));
1879 tokLen = CountRepeat (format, i, ch);
1880 result.Append (dfi.GetEraName (dfi.Calendar.GetEra (this)));
1887 result.Append (dfi.TimeSeparator);
1891 result.Append (dfi.DateSeparator);
1894 case '\'': case '"':
1895 tokLen = ParseQuotedString (format, i, result);
1898 if (i >= format.Length - 1)
1899 throw new FormatException ("% at end of date time string");
1900 if (format [i + 1] == '%')
1901 throw new FormatException ("%% in date string");
1903 // Look for the next char
1908 if (i >= format.Length - 1)
1909 throw new FormatException ("\\ at end of date time string");
1911 result.Append (format [i + 1]);
1923 return result.ToString ();
1926 static int CountRepeat (string fmt, int p, char c)
1930 while ((i < l) && (fmt [i] == c))
1936 static int ParseQuotedString (string fmt, int pos, StringBuilder output)
1938 // pos == position of " or '
1940 int len = fmt.Length;
1942 char quoteChar = fmt [pos++];
1945 char ch = fmt [pos++];
1947 if (ch == quoteChar)
1953 throw new FormatException("Un-ended quote");
1955 output.Append (fmt [pos++]);
1961 throw new FormatException("Un-ended quote");
1964 static unsafe void ZeroPad (StringBuilder output, int digits, int len)
1966 // more than enough for an int
1967 char* buffer = stackalloc char [16];
1971 buffer [-- pos] = (char) ('0' + digits % 10);
1974 } while (digits > 0);
1977 buffer [-- pos] = '0';
1979 output.Append (new string (buffer, pos, 16 - pos));
1982 public string ToString (string format, IFormatProvider fp)
1985 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance(fp);
1990 bool useutc = false, use_invariant = false;
1992 if (format.Length == 1) {
1993 char fchar = format [0];
1994 format = _GetStandardPattern (fchar, dfi, out useutc, out use_invariant);
1997 // Don't convert UTC value. It just adds 'Z' for
1998 // 'u' format, for the same ticks.
1999 return this._ToString (format, dfi);
2002 public DateTime ToLocalTime ()
2004 return TimeZone.CurrentTimeZone.ToLocalTime (this);
2007 public DateTime ToUniversalTime()
2009 return TimeZone.CurrentTimeZone.ToUniversalTime (this);
2014 public static DateTime operator +(DateTime d, TimeSpan t)
2016 DateTime ret = new DateTime (true, d.ticks + t);
2023 public static bool operator ==(DateTime d1, DateTime d2)
2025 return (d1.ticks == d2.ticks);
2028 public static bool operator >(DateTime t1,DateTime t2)
2030 return (t1.ticks > t2.ticks);
2033 public static bool operator >=(DateTime t1,DateTime t2)
2035 return (t1.ticks >= t2.ticks);
2038 public static bool operator !=(DateTime d1, DateTime d2)
2040 return (d1.ticks != d2.ticks);
2043 public static bool operator <(DateTime t1, DateTime t2)
2045 return (t1.ticks < t2.ticks );
2048 public static bool operator <=(DateTime t1,DateTime t2)
2050 return (t1.ticks <= t2.ticks);
2053 public static TimeSpan operator -(DateTime d1,DateTime d2)
2055 return new TimeSpan((d1.ticks - d2.ticks).Ticks);
2058 public static DateTime operator -(DateTime d,TimeSpan t)
2060 DateTime ret = new DateTime (true, d.ticks - t);
2067 bool IConvertible.ToBoolean(IFormatProvider provider)
2069 throw new InvalidCastException();
2072 byte IConvertible.ToByte(IFormatProvider provider)
2074 throw new InvalidCastException();
2078 char IConvertible.ToChar(IFormatProvider provider)
2080 throw new InvalidCastException();
2083 System.DateTime IConvertible.ToDateTime(IFormatProvider provider)
2088 decimal IConvertible.ToDecimal(IFormatProvider provider)
2090 throw new InvalidCastException();
2093 double IConvertible.ToDouble(IFormatProvider provider)
2095 throw new InvalidCastException();
2098 Int16 IConvertible.ToInt16(IFormatProvider provider)
2100 throw new InvalidCastException();
2103 Int32 IConvertible.ToInt32(IFormatProvider provider)
2105 throw new InvalidCastException();
2108 Int64 IConvertible.ToInt64(IFormatProvider provider)
2110 throw new InvalidCastException();
2113 SByte IConvertible.ToSByte(IFormatProvider provider)
2115 throw new InvalidCastException();
2118 Single IConvertible.ToSingle(IFormatProvider provider)
2120 throw new InvalidCastException();
2123 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
2125 if (conversionType == null)
2126 throw new ArgumentNullException ("conversionType");
2128 if (conversionType == typeof (DateTime))
2130 else if (conversionType == typeof (String))
2131 return this.ToString (provider);
2132 else if (conversionType == typeof (Object))
2135 throw new InvalidCastException();
2138 UInt16 IConvertible.ToUInt16(IFormatProvider provider)
2140 throw new InvalidCastException();
2143 UInt32 IConvertible.ToUInt32(IFormatProvider provider)
2145 throw new InvalidCastException();
2148 UInt64 IConvertible.ToUInt64(IFormatProvider provider)
2150 throw new InvalidCastException();