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 return new DateTime (Year, Month, Day);
347 return FromTicks(Which.Month);
356 return FromTicks(Which.Day);
360 public DayOfWeek DayOfWeek
364 return ( (DayOfWeek) ((ticks.Days+1) % 7) );
372 return FromTicks(Which.DayYear);
376 public TimeSpan TimeOfDay
380 return new TimeSpan(ticks.Ticks % TimeSpan.TicksPerDay );
397 return ticks.Minutes;
405 return ticks.Seconds;
409 public int Millisecond
413 return ticks.Milliseconds;
417 [MethodImplAttribute(MethodImplOptions.InternalCall)]
418 internal static extern long GetNow ();
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'
426 static object to_local_time_span_object;
427 static long last_now;
429 public static DateTime Now
433 long now = GetNow ();
434 DateTime dt = new DateTime (now);
436 if ((now - last_now) > TimeSpan.TicksPerMinute){
437 to_local_time_span_object = TimeZone.CurrentTimeZone.GetLocalTimeDiff (dt);
442 // This is boxed, so we avoid locking.
443 DateTime ret = dt + (TimeSpan) to_local_time_span_object;
445 ret.kind = DateTimeKind.Local;
459 public static DateTime Today
463 DateTime today = new DateTime (now.Year, now.Month, now.Day);
465 today.kind = now.kind;
471 public static DateTime UtcNow
475 return new DateTime (GetNow (), DateTimeKind.Utc);
477 return new DateTime (GetNow ());
486 return FromTicks(Which.Year);
491 public DateTimeKind Kind {
500 public DateTime Add (TimeSpan ts)
502 return AddTicks (ts.Ticks);
505 public DateTime AddDays (double days)
507 return AddMilliseconds (Math.Round (days * 86400000));
510 public DateTime AddTicks (long t)
512 if ((t + ticks.Ticks) > MAX_VALUE_TICKS || (t + ticks.Ticks) < 0) {
513 throw new ArgumentOutOfRangeException();
515 return new DateTime (t + ticks.Ticks);
518 public DateTime AddHours (double hours)
520 return AddMilliseconds (hours * 3600000);
523 public DateTime AddMilliseconds (double ms)
525 if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
526 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
527 throw new ArgumentOutOfRangeException();
529 long msticks = (long) (ms * TimeSpan.TicksPerMillisecond);
531 return AddTicks (msticks);
534 // required to match MS implementation for OADate (OLE Automation)
535 private DateTime AddRoundedMilliseconds (double ms)
537 if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
538 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
539 throw new ArgumentOutOfRangeException ();
541 long msticks = (long) (ms += ms > 0 ? 0.5 : -0.5) * TimeSpan.TicksPerMillisecond;
543 return AddTicks (msticks);
546 public DateTime AddMinutes (double minutes)
548 return AddMilliseconds (minutes * 60000);
551 public DateTime AddMonths (int months)
553 int day, month, year, maxday ;
557 month = this.Month + (months % 12);
558 year = this.Year + months/12 ;
570 maxday = DaysInMonth(year, month);
574 temp = new DateTime (year, month, day);
575 return temp.Add (this.TimeOfDay);
578 public DateTime AddSeconds (double seconds)
580 return AddMilliseconds (seconds*1000);
583 public DateTime AddYears (int years )
585 return AddMonths(years * 12);
588 public static int Compare (DateTime t1, DateTime t2)
590 if (t1.ticks < t2.ticks)
592 else if (t1.ticks > t2.ticks)
598 public int CompareTo (object v)
603 if (!(v is System.DateTime))
604 throw new ArgumentException (Locale.GetText (
605 "Value is not a System.DateTime"));
607 return Compare (this, (DateTime) v);
611 public bool IsDaylightSavingTime ()
613 if (kind == DateTimeKind.Utc)
615 return TimeZone.CurrentTimeZone.IsDaylightSavingTime (this);
618 public int CompareTo (DateTime value)
620 return Compare (this, value);
623 public bool Equals (DateTime value)
625 return value.ticks == ticks;
628 public long ToBinary ()
631 case DateTimeKind.Utc:
632 return Ticks | 0x4000000000000000;
633 case DateTimeKind.Local:
634 return (long) ((ulong)Ticks | 0x8000000000000000);
640 public static DateTime FromBinary (long dateData)
642 switch ((ulong)dateData >> 62) {
644 return new DateTime (dateData ^ 0x4000000000000000, DateTimeKind.Utc);
646 return new DateTime (dateData, DateTimeKind.Unspecified);
648 return new DateTime (((dateData << 2) >> 2), DateTimeKind.Local);
652 public static DateTime SpecifyKind (DateTime value, DateTimeKind kind)
654 return new DateTime (value.Ticks, kind);
658 public static int DaysInMonth (int year, int month)
662 if (month < 1 || month >12)
663 throw new ArgumentOutOfRangeException ();
665 days = (IsLeapYear(year) ? daysmonthleap : daysmonth);
669 public override bool Equals (object o)
671 if (!(o is System.DateTime))
674 return ((DateTime) o).ticks == ticks;
677 public static bool Equals (DateTime t1, DateTime t2 )
679 return (t1.ticks == t2.ticks );
682 public static DateTime FromFileTime (long fileTime)
685 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
687 return new DateTime (w32file_epoch + fileTime).ToLocalTime ();
691 public static DateTime FromFileTimeUtc (long fileTime)
694 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
696 return new DateTime (w32file_epoch + fileTime);
700 public static DateTime FromOADate (double d)
702 // An OLE Automation date is implemented as a floating-point number
703 // whose value is the number of days from midnight, 30 December 1899.
705 // d must be negative 657435.0 through positive 2958466.0.
706 if ((d <= OAMinValue) || (d >= OAMaxValue))
707 throw new ArgumentException ("d", "[-657435,2958466]");
709 DateTime dt = new DateTime (ticks18991230);
711 Double days = Math.Ceiling (d);
712 // integer part is the number of days (negative)
713 dt = dt.AddRoundedMilliseconds (days * 86400000);
714 // but decimals are the number of hours (in days fractions) and positive
715 Double hours = (days - d);
716 dt = dt.AddRoundedMilliseconds (hours * 86400000);
719 dt = dt.AddRoundedMilliseconds (d * 86400000);
725 public string[] GetDateTimeFormats()
727 return GetDateTimeFormats (CultureInfo.CurrentCulture);
730 public string[] GetDateTimeFormats(char format)
732 if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
733 throw new FormatException ("Invalid format character.");
734 string[] result = new string[1];
735 result[0] = this.ToString(format.ToString());
739 public string[] GetDateTimeFormats(IFormatProvider provider)
741 DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
742 // return GetDateTimeFormats (info.GetAllDateTimePatterns ());
743 ArrayList al = new ArrayList ();
744 foreach (char c in "dDgGfFmMrRstTuUyY")
745 al.AddRange (GetDateTimeFormats (c, info));
746 return al.ToArray (typeof (string)) as string [];
749 public string[] GetDateTimeFormats(char format,IFormatProvider provider )
751 if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
752 throw new FormatException ("Invalid format character.");
754 // LAMESPEC: There is NO assurance that 'U' ALWAYS
755 // euqals to 'F', but since we have to iterate all
756 // the pattern strings, we cannot just use
757 // ToString("U", provider) here. I believe that the
758 // method's behavior cannot be formalized.
759 bool adjustutc = false;
768 DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
769 return GetDateTimeFormats (adjustutc, info.GetAllRawDateTimePatterns (format), info);
772 private string [] GetDateTimeFormats (bool adjustutc, string [] patterns, DateTimeFormatInfo dfi)
774 string [] results = new string [patterns.Length];
775 DateTime val = adjustutc ? ToUniversalTime () : this;
776 for (int i = 0; i < results.Length; i++)
777 results [i] = val._ToString (patterns [i], dfi);
782 private void CheckDateTimeKind (DateTimeKind kind) {
783 if ((kind != DateTimeKind.Unspecified) && (kind != DateTimeKind.Utc) && (kind != DateTimeKind.Local))
784 throw new ArgumentException ("Invalid DateTimeKind value.", "kind");
788 public override int GetHashCode ()
790 return (int) ticks.Ticks;
793 public TypeCode GetTypeCode ()
795 return TypeCode.DateTime;
798 public static bool IsLeapYear (int year)
800 return ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
803 public static DateTime Parse (string s)
805 return Parse (s, null);
808 public static DateTime Parse (string s, IFormatProvider fp)
810 return Parse (s, fp, DateTimeStyles.AllowWhiteSpaces);
813 public static DateTime Parse (string s, IFormatProvider fp, DateTimeStyles styles)
815 // This method should try only expected patterns.
816 // Should not try extra patterns.
817 // Right now we also try InvariantCulture, but I
818 // confirmed in some cases this method rejects what
819 // InvariantCulture supports (can be checked against
820 // "th-TH" with Gregorian Calendar). So basically it
821 // should not be done.
822 // I think it should be CurrentCulture to be tested,
823 // but right now we don't support all the supported
824 // patterns for each culture, so try InvariantCulture
825 // as a quick remedy.
827 throw new ArgumentNullException (Locale.GetText ("s is null"));
831 fp = CultureInfo.CurrentCulture;
832 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
834 bool longYear = false;
836 // Try all the patterns
837 if (ParseExact (s, dfi.GetAllDateTimePatternsInternal (), dfi, styles, out result, false, ref longYear))
840 // Try common formats.
841 // if (ParseExact (s, commonFormats, dfi, styles, out result, false, ref longYear))
844 // Try common formats with invariant culture
845 if (ParseExact (s, commonFormats, DateTimeFormatInfo.InvariantInfo, styles, out result, false, ref longYear))
849 throw new ArgumentOutOfRangeException ("year",
850 "Valid values are between 1 and 9999 inclusive");
853 throw new FormatException ("String was not recognized as a valid DateTime.");
856 public static DateTime ParseExact (string s, string format, IFormatProvider fp)
858 return ParseExact (s, format, fp, DateTimeStyles.None);
861 internal static int _ParseNumber (string s, int valuePos,
875 for (i = valuePos; i < s.Length && i < digits + valuePos; i++) {
876 if (!Char.IsDigit (s[i]))
882 digits = real_digits;
884 if (digits < min_digits) {
889 if (s.Length - valuePos < digits) {
894 for (i = valuePos; i < digits + valuePos; i++) {
896 if (!Char.IsDigit (c)) {
901 number = number * 10 + (byte) (c - '0');
908 internal static int _ParseEnum (string s, int sPos, string[] values, out int num_parsed)
912 // FIXME: I know this is somehow lame code. Probably
913 // it should iterate all the enum value and return
914 // the longest match. However right now I don't see
915 // anything but "1" and "10" - "12" that might match
916 // two or more values. (They are only abbrev month
917 // names, so do reverse order search). See bug #80094.
918 for (i = values.Length - 1; i >= 0; i--) {
919 if (s.Length - sPos < values[i].Length)
921 else if (values [i].Length == 0)
923 String tmp = s.Substring (sPos, values[i].Length);
924 if (String.Compare (tmp, values[i], true) == 0) {
925 num_parsed = values[i].Length;
934 internal static bool _ParseString (string s, int sPos, int maxlength, string value, out int num_parsed)
937 maxlength = value.Length;
939 if (String.Compare (s, sPos, value, 0, maxlength, true, CultureInfo.InvariantCulture) == 0) {
940 num_parsed = maxlength;
948 private static bool _DoParse (string s, string format, bool exact,
950 DateTimeFormatInfo dfi,
951 DateTimeStyles style,
954 bool useutc = false, use_localtime = true;
955 bool use_invariant = false;
956 bool sloppy_parsing = false;
958 if (format.Length == 1)
959 format = _GetStandardPattern (format [0], dfi, out useutc, out use_invariant);
960 else if (!exact && CultureInfo.InvariantCulture.CompareInfo.IndexOf (format, "GMT", CompareOptions.Ordinal) >= 0)
963 if ((style & DateTimeStyles.AllowLeadingWhite) != 0) {
964 format = format.TrimStart (null);
966 s = s.TrimStart (null); // it could be optimized, but will make little good.
969 if ((style & DateTimeStyles.AllowTrailingWhite) != 0) {
970 format = format.TrimEnd (null);
971 s = s.TrimEnd (null); // it could be optimized, but will make little good.
975 dfi = DateTimeFormatInfo.InvariantInfo;
977 if ((style & DateTimeStyles.AllowInnerWhite) != 0)
978 sloppy_parsing = true;
980 string chars = format;
981 int len = format.Length, pos = 0, num = 0;
983 int day = -1, dayofweek = -1, month = -1, year = -1;
984 int hour = -1, minute = -1, second = -1;
985 double fractionalSeconds = -1;
987 int tzsign = -1, tzoffset = -1, tzoffmin = -1;
989 result = new DateTime (0);
990 while (pos+num < len)
992 if (s.Length == valuePos)
995 if (chars[pos] == '\'') {
997 while (pos+num < len) {
998 if (chars[pos+num] == '\'')
1001 if (valuePos == s.Length)
1003 if (s [valuePos] != chars [pos + num])
1015 } else if (chars[pos] == '"') {
1017 while (pos+num < len) {
1018 if (chars[pos+num] == '"')
1021 if (valuePos == s.Length)
1023 if (s [valuePos] != chars[pos+num])
1035 } else if (chars[pos] == '\\') {
1041 if (s [valuePos] != chars [pos])
1046 } else if (chars[pos] == '%') {
1049 } else if (Char.IsWhiteSpace (s [valuePos]) ||
1050 s [valuePos] == ',' && Char.IsWhiteSpace (chars [pos])) {
1053 if (exact && (style & DateTimeStyles.AllowInnerWhite) == 0) {
1054 if (!Char.IsWhiteSpace (chars[pos]))
1061 while (ws < s.Length) {
1062 if (Char.IsWhiteSpace (s [ws]) || s [ws] == ',')
1069 while (ws < chars.Length) {
1070 if (Char.IsWhiteSpace (chars [ws]) || chars [ws] == ',')
1079 if ((pos+num+1 < len) && (chars[pos+num+1] == chars[pos+num])) {
1093 day = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1095 day = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1097 dayofweek = _ParseEnum (s, valuePos, dfi.RawAbbreviatedDayNames, out num_parsed);
1100 dayofweek = _ParseEnum (s, valuePos, dfi.RawDayNames, out num_parsed);
1108 month = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1110 month = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1112 month = _ParseEnum (s, valuePos, dfi.RawAbbreviatedMonthNames , out num_parsed) + 1;
1115 month = _ParseEnum (s, valuePos, dfi.RawMonthNames, out num_parsed) + 1;
1124 year = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1125 } else if (num < 3) {
1126 year = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1128 year = _ParseNumber (s, valuePos,4, 4, false, sloppy_parsing, out num_parsed);
1129 if ((year >= 1000) && (num_parsed == 4) && (!longYear) && (s.Length > 4 + valuePos)) {
1131 int ly = _ParseNumber (s, valuePos, 5, 5, false, sloppy_parsing, out np);
1132 longYear = (ly > 9999);
1137 //FIXME: We should do use dfi.Calendat.TwoDigitYearMax
1138 if (num_parsed <= 2)
1139 year += (year < 30) ? 2000 : 1900;
1145 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1148 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1159 if ((hour != -1) || (ampm >= 0))
1162 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1165 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1177 minute = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1180 minute = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1191 second = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1194 second = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1202 if (fractionalSeconds != -1)
1204 num = Math.Min (num, 6);
1205 double decimalNumber = (double) _ParseNumber (s, valuePos, 0, num+1, true, sloppy_parsing, out num_parsed);
1206 if (num_parsed == -1)
1210 fractionalSeconds = decimalNumber / Math.Pow(10.0, num_parsed);
1217 if (_ParseString (s, valuePos, 1, dfi.AMDesignator, out num_parsed))
1219 else if (_ParseString (s, valuePos, 1, dfi.PMDesignator, out num_parsed))
1226 if (_ParseString (s, valuePos, 0, dfi.AMDesignator, out num_parsed))
1228 else if (_ParseString (s, valuePos, 0, dfi.PMDesignator, out num_parsed))
1238 if (s [valuePos] == '+')
1240 else if (s [valuePos] == '-')
1246 tzoffset = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1248 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1251 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1254 valuePos += num_parsed;
1255 if (Char.IsDigit (s [valuePos]))
1257 else if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1259 valuePos += num_parsed;
1260 tzoffmin = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1267 // LAMESPEC: This should be part of UTCpattern
1268 // string and thus should not be considered here.
1270 // Note that 'Z' is not defined as a pattern
1271 // character. Keep it for X509 certificate
1272 // verification. Also, "Z" != "'Z'" under MS.NET
1273 // ("'Z'" is just literal; handled above)
1275 if (s [valuePos] != 'Z')
1283 if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1287 /* Accept any character for
1288 * DateSeparator, except
1289 * TimeSeparator, a digit or a
1290 * letter. Not documented,
1291 * but seems to be MS
1292 * behaviour here. See bug
1295 if (exact && s [valuePos] != '/')
1298 if (_ParseString (s, valuePos, 0,
1301 Char.IsDigit (s [valuePos]) ||
1302 Char.IsLetter (s [valuePos])) {
1307 if (num_parsed <= 0) {
1313 if (s [valuePos] != chars[pos]) {
1314 // FIXME: It is not sure, but
1315 // IsLetter() is introduced
1316 // because we have to reject
1317 // "2002a02b25" but have to
1318 // allow "2002$02$25". The same
1319 // thing applies to '/' case.
1321 Char.IsDigit (s [valuePos]) ||
1322 Char.IsLetter (s [valuePos]))
1333 valuePos += num_parsed;
1336 switch (chars [pos]) {
1341 if (s.Length > valuePos && s [valuePos] == 'Z'
1342 && (pos + 1 == chars.Length
1343 || chars [pos + 1] != 'Z')) {
1351 pos = pos + num + 1;
1355 // possible empty value. Regarded as no match.
1362 if (s.Length != valuePos) // extraneous tail.
1372 if (fractionalSeconds == -1)
1373 fractionalSeconds = 0;
1375 // If no date was given
1376 if ((day == -1) && (month == -1) && (year == -1)) {
1377 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
1383 month = Today.Month;
1394 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
1403 // For anything out of range
1405 if ( year < 1 || year > 9999 ||
1406 month < 1 || month >12 ||
1407 day < 1 || day > DaysInMonth(year, month) ||
1408 hour < 0 || hour > 23 ||
1409 minute < 0 || minute > 59 ||
1410 second < 0 || second > 59 )
1413 result = new DateTime (year, month, day, hour, minute, second, 0);
1414 result = result.AddSeconds(fractionalSeconds);
1416 if ((dayofweek != -1) && (dayofweek != (int) result.DayOfWeek))
1417 throw new FormatException (Locale.GetText ("String was not recognized as valid DateTime because the day of week was incorrect."));
1419 // If no timezone was specified, default to the local timezone.
1423 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1424 use_localtime = false;
1425 utcoffset = new TimeSpan (0, 0, 0);
1426 } else if (tzsign == -1) {
1427 TimeZone tz = TimeZone.CurrentTimeZone;
1428 utcoffset = tz.GetUtcOffset (result);
1430 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1431 use_localtime = false;
1438 tzoffset = -tzoffset
1440 utcoffset = new TimeSpan (tzoffset, tzoffmin, 0);
1443 long newticks = (result.ticks - utcoffset).Ticks;
1445 result = new DateTime (false, new TimeSpan (newticks));
1447 result = result.ToLocalTime ();
1453 public static DateTime ParseExact (string s, string format,
1454 IFormatProvider fp, DateTimeStyles style)
1458 formats = new string [1];
1459 formats[0] = format;
1461 return ParseExact (s, formats, fp, style);
1464 public static DateTime ParseExact (string s, string[] formats,
1466 DateTimeStyles style)
1468 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1471 throw new ArgumentNullException (Locale.GetText ("s is null"));
1472 if (formats == null || formats.Length == 0)
1473 throw new ArgumentNullException (Locale.GetText ("format is null"));
1476 bool longYear = false;
1477 if (!ParseExact (s, formats, dfi, style, out result, true, ref longYear))
1478 throw new FormatException ();
1483 public static bool TryParse (string s, out DateTime result)
1494 public static bool TryParse (string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
1497 result = Parse (s, provider, styles);
1505 public static bool TryParseExact (string s, string format,
1507 DateTimeStyles style,
1508 out DateTime result)
1512 formats = new string [1];
1513 formats[0] = format;
1515 return TryParseExact (s, formats, fp, style, out result);
1518 public static bool TryParseExact (string s, string[] formats,
1520 DateTimeStyles style,
1521 out DateTime result)
1523 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1525 bool longYear = false;
1526 return ParseExact (s, formats, dfi, style, out result, true, ref longYear);
1530 private static bool ParseExact (string s, string [] formats,
1531 DateTimeFormatInfo dfi, DateTimeStyles style, out DateTime ret,
1532 bool exact, ref bool longYear)
1535 for (i = 0; i < formats.Length; i++)
1539 if (_DoParse (s, formats[i], exact, out result, dfi, style, ref longYear)) {
1544 ret = DateTime.MinValue;
1548 public TimeSpan Subtract(DateTime dt)
1550 return new TimeSpan(ticks.Ticks) - dt.ticks;
1553 public DateTime Subtract(TimeSpan ts)
1557 newticks = (new TimeSpan (ticks.Ticks)) - ts;
1558 return new DateTime(true,newticks);
1561 public long ToFileTime()
1563 DateTime universalTime = ToUniversalTime();
1565 if (universalTime.Ticks < w32file_epoch) {
1566 throw new ArgumentOutOfRangeException("file time is not valid");
1569 return(universalTime.Ticks - w32file_epoch);
1573 public long ToFileTimeUtc()
1575 if (Ticks < w32file_epoch) {
1576 throw new ArgumentOutOfRangeException("file time is not valid");
1579 return (Ticks - w32file_epoch);
1583 public string ToLongDateString()
1585 return ToString ("D");
1588 public string ToLongTimeString()
1590 return ToString ("T");
1593 public double ToOADate ()
1595 long t = this.Ticks;
1596 // uninitialized DateTime case
1599 // we can't reach minimum value
1600 if (t < 31242239136000000)
1601 return OAMinValue + 0.001;
1603 TimeSpan ts = new TimeSpan (this.Ticks - ticks18991230);
1604 double result = ts.TotalDays;
1605 // t < 0 (where 599264352000000000 == 0.0d for OA)
1606 if (t < 599264352000000000) {
1607 // negative days (int) but decimals are positive
1608 double d = Math.Ceiling (result);
1609 result = d - 2 - (result - d);
1612 // we can't reach maximum value
1613 if (result >= OAMaxValue)
1614 result = OAMaxValue - 0.00000001d;
1619 public string ToShortDateString()
1621 return ToString ("d");
1624 public string ToShortTimeString()
1626 return ToString ("t");
1629 public override string ToString ()
1631 return ToString ("G", null);
1634 public string ToString (IFormatProvider fp)
1636 return ToString (null, fp);
1639 public string ToString (string format)
1641 return ToString (format, null);
1644 internal static string _GetStandardPattern (char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant)
1649 use_invariant = false;
1654 pattern = dfi.ShortDatePattern;
1657 pattern = dfi.LongDatePattern;
1660 pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
1663 pattern = dfi.FullDateTimePattern;
1666 pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
1669 pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
1673 pattern = dfi.MonthDayPattern;
1677 pattern = dfi.RFC1123Pattern;
1678 // commented by LP 09/jun/2002, rfc 1123 pattern is always in GMT
1679 // uncommented by AE 27/may/2004
1681 use_invariant = true;
1684 pattern = dfi.SortableDateTimePattern;
1687 pattern = dfi.ShortTimePattern;
1690 pattern = dfi.LongTimePattern;
1693 pattern = dfi.UniversalSortableDateTimePattern;
1697 // pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
1698 pattern = dfi.FullDateTimePattern;
1703 pattern = dfi.YearMonthPattern;
1713 internal string _ToString (string format, DateTimeFormatInfo dfi)
1715 // the length of the format is usually a good guess of the number
1716 // of chars in the result. Might save us a few bytes sometimes
1717 // Add + 10 for cases like mmmm dddd
1718 StringBuilder result = new StringBuilder (format.Length + 10);
1720 // For some cases, the output should not use culture dependent calendar
1721 DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo;
1722 if (format == inv.RFC1123Pattern)
1724 else if (format == inv.UniversalSortableDateTimePattern)
1729 while (i < format.Length) {
1731 char ch = format [i];
1740 tokLen = CountRepeat (format, i, ch);
1742 int hr = this.Hour % 12;
1746 ZeroPad (result, hr, tokLen == 1 ? 1 : 2);
1750 tokLen = CountRepeat (format, i, ch);
1751 ZeroPad (result, this.Hour, tokLen == 1 ? 1 : 2);
1755 tokLen = CountRepeat (format, i, ch);
1756 ZeroPad (result, this.Minute, tokLen == 1 ? 1 : 2);
1760 tokLen = CountRepeat (format, i, ch);
1761 ZeroPad (result, this.Second, tokLen == 1 ? 1 : 2);
1764 // fraction of second, to same number of
1765 // digits as there are f's
1767 tokLen = CountRepeat (format, i, ch);
1769 throw new FormatException ("Invalid Format String");
1771 int dec = (int)((long)(this.Ticks % TimeSpan.TicksPerSecond) / (long) Math.Pow (10, 7 - tokLen));
1772 ZeroPad (result, dec, tokLen);
1776 // AM/PM. t == first char, tt+ == full
1777 tokLen = CountRepeat (format, i, ch);
1778 string desig = this.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator;
1781 if (desig.Length >= 1)
1782 result.Append (desig [0]);
1785 result.Append (desig);
1789 // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm
1790 tokLen = CountRepeat (format, i, ch);
1791 TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset (this);
1793 if (offset.Ticks >= 0)
1794 result.Append ('+');
1796 result.Append ('-');
1800 result.Append (Math.Abs (offset.Hours));
1803 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1806 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1807 result.Append (':');
1808 result.Append (Math.Abs (offset.Minutes).ToString ("00"));
1816 // day. d(d?) = day of month (leading 0 if two d's)
1817 // ddd = three leter day of week
1818 // dddd+ full day-of-week
1819 tokLen = CountRepeat (format, i, ch);
1822 ZeroPad (result, dfi.Calendar.GetDayOfMonth (this), tokLen == 1 ? 1 : 2);
1823 else if (tokLen == 3)
1824 result.Append (dfi.GetAbbreviatedDayName (dfi.Calendar.GetDayOfWeek (this)));
1826 result.Append (dfi.GetDayName (dfi.Calendar.GetDayOfWeek (this)));
1830 // Month.m(m?) = month # (with leading 0 if two mm)
1831 // mmm = 3 letter name
1832 // mmmm+ = full name
1833 tokLen = CountRepeat (format, i, ch);
1834 int month = dfi.Calendar.GetMonth(this);
1836 ZeroPad (result, month, tokLen);
1837 else if (tokLen == 3)
1838 result.Append (dfi.GetAbbreviatedMonthName (month));
1840 result.Append (dfi.GetMonthName (month));
1844 // Year. y(y?) = two digit year, with leading 0 if yy
1845 // yyy+ full year, if yyy and yr < 1000, displayed as three digits
1846 tokLen = CountRepeat (format, i, ch);
1849 ZeroPad (result, dfi.Calendar.GetYear (this) % 100, tokLen);
1851 ZeroPad (result, dfi.Calendar.GetYear (this), (tokLen == 3 ? 3 : 4));
1856 tokLen = CountRepeat (format, i, ch);
1857 result.Append (dfi.GetEraName (dfi.Calendar.GetEra (this)));
1864 result.Append (dfi.TimeSeparator);
1868 result.Append (dfi.DateSeparator);
1871 case '\'': case '"':
1872 tokLen = ParseQuotedString (format, i, result);
1875 if (i >= format.Length - 1)
1876 throw new FormatException ("% at end of date time string");
1877 if (format [i + 1] == '%')
1878 throw new FormatException ("%% in date string");
1880 // Look for the next char
1885 if (i >= format.Length - 1)
1886 throw new FormatException ("\\ at end of date time string");
1888 result.Append (format [i + 1]);
1900 return result.ToString ();
1903 static int CountRepeat (string fmt, int p, char c)
1907 while ((i < l) && (fmt [i] == c))
1913 static int ParseQuotedString (string fmt, int pos, StringBuilder output)
1915 // pos == position of " or '
1917 int len = fmt.Length;
1919 char quoteChar = fmt [pos++];
1922 char ch = fmt [pos++];
1924 if (ch == quoteChar)
1930 throw new FormatException("Un-ended quote");
1932 output.Append (fmt [pos++]);
1938 throw new FormatException("Un-ended quote");
1941 static unsafe void ZeroPad (StringBuilder output, int digits, int len)
1943 // more than enough for an int
1944 char* buffer = stackalloc char [16];
1948 buffer [-- pos] = (char) ('0' + digits % 10);
1951 } while (digits > 0);
1954 buffer [-- pos] = '0';
1956 output.Append (new string (buffer, pos, 16 - pos));
1959 public string ToString (string format, IFormatProvider fp)
1962 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance(fp);
1967 bool useutc = false, use_invariant = false;
1969 if (format.Length == 1) {
1970 char fchar = format [0];
1971 format = _GetStandardPattern (fchar, dfi, out useutc, out use_invariant);
1974 // Don't convert UTC value. It just adds 'Z' for
1975 // 'u' format, for the same ticks.
1976 return this._ToString (format, dfi);
1979 public DateTime ToLocalTime ()
1981 return TimeZone.CurrentTimeZone.ToLocalTime (this);
1984 public DateTime ToUniversalTime()
1986 return TimeZone.CurrentTimeZone.ToUniversalTime (this);
1991 public static DateTime operator +(DateTime d, TimeSpan t)
1993 return new DateTime (true, d.ticks + t);
1996 public static bool operator ==(DateTime d1, DateTime d2)
1998 return (d1.ticks == d2.ticks);
2001 public static bool operator >(DateTime t1,DateTime t2)
2003 return (t1.ticks > t2.ticks);
2006 public static bool operator >=(DateTime t1,DateTime t2)
2008 return (t1.ticks >= t2.ticks);
2011 public static bool operator !=(DateTime d1, DateTime d2)
2013 return (d1.ticks != d2.ticks);
2016 public static bool operator <(DateTime t1, DateTime t2)
2018 return (t1.ticks < t2.ticks );
2021 public static bool operator <=(DateTime t1,DateTime t2)
2023 return (t1.ticks <= t2.ticks);
2026 public static TimeSpan operator -(DateTime d1,DateTime d2)
2028 return new TimeSpan((d1.ticks - d2.ticks).Ticks);
2031 public static DateTime operator -(DateTime d,TimeSpan t)
2033 return new DateTime (true, d.ticks - t);
2036 bool IConvertible.ToBoolean(IFormatProvider provider)
2038 throw new InvalidCastException();
2041 byte IConvertible.ToByte(IFormatProvider provider)
2043 throw new InvalidCastException();
2047 char IConvertible.ToChar(IFormatProvider provider)
2049 throw new InvalidCastException();
2052 System.DateTime IConvertible.ToDateTime(IFormatProvider provider)
2057 decimal IConvertible.ToDecimal(IFormatProvider provider)
2059 throw new InvalidCastException();
2062 double IConvertible.ToDouble(IFormatProvider provider)
2064 throw new InvalidCastException();
2067 Int16 IConvertible.ToInt16(IFormatProvider provider)
2069 throw new InvalidCastException();
2072 Int32 IConvertible.ToInt32(IFormatProvider provider)
2074 throw new InvalidCastException();
2077 Int64 IConvertible.ToInt64(IFormatProvider provider)
2079 throw new InvalidCastException();
2082 SByte IConvertible.ToSByte(IFormatProvider provider)
2084 throw new InvalidCastException();
2087 Single IConvertible.ToSingle(IFormatProvider provider)
2089 throw new InvalidCastException();
2092 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
2094 if (conversionType == null)
2095 throw new ArgumentNullException ("conversionType");
2097 if (conversionType == typeof (DateTime))
2099 else if (conversionType == typeof (String))
2100 return this.ToString (provider);
2101 else if (conversionType == typeof (Object))
2104 throw new InvalidCastException();
2107 UInt16 IConvertible.ToUInt16(IFormatProvider provider)
2109 throw new InvalidCastException();
2112 UInt32 IConvertible.ToUInt32(IFormatProvider provider)
2114 throw new InvalidCastException();
2117 UInt64 IConvertible.ToUInt64(IFormatProvider provider)
2119 throw new InvalidCastException();