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-2005 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 return dt + (TimeSpan) to_local_time_span_object;
455 public static DateTime Today
459 DateTime today = new DateTime (now.Year, now.Month, now.Day);
461 today.kind = now.kind;
467 public static DateTime UtcNow
471 return new DateTime (GetNow (), DateTimeKind.Utc);
473 return new DateTime (GetNow ());
482 return FromTicks(Which.Year);
487 public DateTimeKind Kind {
496 public DateTime Add (TimeSpan ts)
498 return AddTicks (ts.Ticks);
501 public DateTime AddDays (double days)
503 return AddMilliseconds (Math.Round (days * 86400000));
506 public DateTime AddTicks (long t)
508 if ((t + ticks.Ticks) > MAX_VALUE_TICKS || (t + ticks.Ticks) < 0) {
509 throw new ArgumentOutOfRangeException();
511 return new DateTime (t + ticks.Ticks);
514 public DateTime AddHours (double hours)
516 return AddMilliseconds (hours * 3600000);
519 public DateTime AddMilliseconds (double ms)
521 if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
522 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
523 throw new ArgumentOutOfRangeException();
525 long msticks = (long) (ms * TimeSpan.TicksPerMillisecond);
527 return AddTicks (msticks);
530 // required to match MS implementation for OADate (OLE Automation)
531 private DateTime AddRoundedMilliseconds (double ms)
533 if ((ms * TimeSpan.TicksPerMillisecond) > long.MaxValue ||
534 (ms * TimeSpan.TicksPerMillisecond) < long.MinValue) {
535 throw new ArgumentOutOfRangeException ();
537 long msticks = (long) (ms += ms > 0 ? 0.5 : -0.5) * TimeSpan.TicksPerMillisecond;
539 return AddTicks (msticks);
542 public DateTime AddMinutes (double minutes)
544 return AddMilliseconds (minutes * 60000);
547 public DateTime AddMonths (int months)
549 int day, month, year, maxday ;
553 month = this.Month + (months % 12);
554 year = this.Year + months/12 ;
566 maxday = DaysInMonth(year, month);
570 temp = new DateTime (year, month, day);
571 return temp.Add (this.TimeOfDay);
574 public DateTime AddSeconds (double seconds)
576 return AddMilliseconds (seconds*1000);
579 public DateTime AddYears (int years )
581 return AddMonths(years * 12);
584 public static int Compare (DateTime t1, DateTime t2)
586 if (t1.ticks < t2.ticks)
588 else if (t1.ticks > t2.ticks)
594 public int CompareTo (object v)
599 if (!(v is System.DateTime))
600 throw new ArgumentException (Locale.GetText (
601 "Value is not a System.DateTime"));
603 return Compare (this, (DateTime) v);
607 public bool IsDaylightSavingTime ()
609 if (kind == DateTimeKind.Utc)
611 return TimeZone.CurrentTimeZone.IsDaylightSavingTime (this);
614 public int CompareTo (DateTime value)
616 return Compare (this, value);
619 public bool Equals (DateTime value)
621 return value.ticks == ticks;
624 public static DateTime SpecifyKind (DateTime value, DateTimeKind kind)
626 return new DateTime (value.Ticks, kind);
630 public static int DaysInMonth (int year, int month)
634 if (month < 1 || month >12)
635 throw new ArgumentOutOfRangeException ();
637 days = (IsLeapYear(year) ? daysmonthleap : daysmonth);
641 public override bool Equals (object o)
643 if (!(o is System.DateTime))
646 return ((DateTime) o).ticks == ticks;
649 public static bool Equals (DateTime t1, DateTime t2 )
651 return (t1.ticks == t2.ticks );
654 public static DateTime FromFileTime (long fileTime)
657 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
659 return new DateTime (w32file_epoch + fileTime).ToLocalTime ();
663 public static DateTime FromFileTimeUtc (long fileTime)
666 throw new ArgumentOutOfRangeException ("fileTime", "< 0");
668 return new DateTime (w32file_epoch + fileTime);
672 public static DateTime FromOADate (double d)
674 // An OLE Automation date is implemented as a floating-point number
675 // whose value is the number of days from midnight, 30 December 1899.
677 // d must be negative 657435.0 through positive 2958466.0.
678 if ((d <= OAMinValue) || (d >= OAMaxValue))
679 throw new ArgumentException ("d", "[-657435,2958466]");
681 DateTime dt = new DateTime (ticks18991230);
683 Double days = Math.Ceiling (d);
684 // integer part is the number of days (negative)
685 dt = dt.AddRoundedMilliseconds (days * 86400000);
686 // but decimals are the number of hours (in days fractions) and positive
687 Double hours = (days - d);
688 dt = dt.AddRoundedMilliseconds (hours * 86400000);
691 dt = dt.AddRoundedMilliseconds (d * 86400000);
697 public string[] GetDateTimeFormats()
699 return GetDateTimeFormats (CultureInfo.CurrentCulture);
702 public string[] GetDateTimeFormats(char format)
704 if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
705 throw new FormatException ("Invalid format character.");
706 string[] result = new string[1];
707 result[0] = this.ToString(format.ToString());
711 public string[] GetDateTimeFormats(IFormatProvider provider)
713 DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
714 // return GetDateTimeFormats (info.GetAllDateTimePatterns ());
715 ArrayList al = new ArrayList ();
716 foreach (char c in "dDgGfFmMrRstTuUyY")
717 al.AddRange (GetDateTimeFormats (c, info));
718 return al.ToArray (typeof (string)) as string [];
721 public string[] GetDateTimeFormats(char format,IFormatProvider provider )
723 if ("dDgGfFmMrRstTuUyY".IndexOf (format) < 0)
724 throw new FormatException ("Invalid format character.");
726 // LAMESPEC: There is NO assurance that 'U' ALWAYS
727 // euqals to 'F', but since we have to iterate all
728 // the pattern strings, we cannot just use
729 // ToString("U", provider) here. I believe that the
730 // method's behavior cannot be formalized.
731 bool adjustutc = false;
740 DateTimeFormatInfo info = (DateTimeFormatInfo) provider.GetFormat (typeof(DateTimeFormatInfo));
741 return GetDateTimeFormats (adjustutc, info.GetAllRawDateTimePatterns (format), info);
744 private string [] GetDateTimeFormats (bool adjustutc, string [] patterns, DateTimeFormatInfo dfi)
746 string [] results = new string [patterns.Length];
747 DateTime val = adjustutc ? ToUniversalTime () : this;
748 for (int i = 0; i < results.Length; i++)
749 results [i] = val._ToString (patterns [i], dfi);
754 private void CheckDateTimeKind (DateTimeKind kind) {
755 if ((kind != DateTimeKind.Unspecified) && (kind != DateTimeKind.Utc) && (kind != DateTimeKind.Local))
756 throw new ArgumentException ("Invalid DateTimeKind value.", "kind");
760 public override int GetHashCode ()
762 return (int) ticks.Ticks;
765 public TypeCode GetTypeCode ()
767 return TypeCode.DateTime;
770 public static bool IsLeapYear (int year)
772 return ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
775 public static DateTime Parse (string s)
777 return Parse (s, null);
780 public static DateTime Parse (string s, IFormatProvider fp)
782 return Parse (s, fp, DateTimeStyles.AllowWhiteSpaces);
785 public static DateTime Parse (string s, IFormatProvider fp, DateTimeStyles styles)
787 // This method should try only expected patterns.
788 // Should not try extra patterns.
789 // Right now we also try InvariantCulture, but I
790 // confirmed in some cases this method rejects what
791 // InvariantCulture supports (can be checked against
792 // "th-TH" with Gregorian Calendar). So basically it
793 // should not be done.
794 // I think it should be CurrentCulture to be tested,
795 // but right now we don't support all the supported
796 // patterns for each culture, so try InvariantCulture
797 // as a quick remedy.
799 throw new ArgumentNullException (Locale.GetText ("s is null"));
803 fp = CultureInfo.CurrentCulture;
804 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
806 bool longYear = false;
808 // Try all the patterns
809 if (ParseExact (s, dfi.GetAllDateTimePatternsInternal (), dfi, styles, out result, false, ref longYear))
812 // Try common formats.
813 // if (ParseExact (s, commonFormats, dfi, styles, out result, false, ref longYear))
816 // Try common formats with invariant culture
817 if (ParseExact (s, commonFormats, DateTimeFormatInfo.InvariantInfo, styles, out result, false, ref longYear))
821 throw new ArgumentOutOfRangeException ("year",
822 "Valid values are between 1 and 9999 inclusive");
825 throw new FormatException ("String was not recognized as a valid DateTime.");
828 public static DateTime ParseExact (string s, string format, IFormatProvider fp)
830 return ParseExact (s, format, fp, DateTimeStyles.None);
833 internal static int _ParseNumber (string s, int valuePos,
847 for (i = valuePos; i < s.Length && i < digits + valuePos; i++) {
848 if (!Char.IsDigit (s[i]))
854 digits = real_digits;
856 if (digits < min_digits) {
861 if (s.Length - valuePos < digits) {
866 for (i = valuePos; i < digits + valuePos; i++) {
868 if (!Char.IsDigit (c)) {
873 number = number * 10 + (byte) (c - '0');
880 internal static int _ParseEnum (string s, int sPos, string[] values, out int num_parsed)
884 for (i = 0; i < values.Length; i++) {
885 if (s.Length - sPos < values[i].Length)
887 else if (values [i].Length == 0)
889 String tmp = s.Substring (sPos, values[i].Length);
890 if (String.Compare (tmp, values[i], true) == 0) {
891 num_parsed = values[i].Length;
900 internal static bool _ParseString (string s, int sPos, int maxlength, string value, out int num_parsed)
903 maxlength = value.Length;
905 if (String.Compare (s, sPos, value, 0, maxlength, true, CultureInfo.InvariantCulture) == 0) {
906 num_parsed = maxlength;
914 private static bool _DoParse (string s, string format, bool exact,
916 DateTimeFormatInfo dfi,
917 DateTimeStyles style,
920 bool useutc = false, use_localtime = true;
921 bool use_invariant = false;
922 bool sloppy_parsing = false;
924 if (format.Length == 1)
925 format = _GetStandardPattern (format [0], dfi, out useutc, out use_invariant);
926 else if (!exact && CultureInfo.InvariantCulture.CompareInfo.IndexOf (format, "GMT", CompareOptions.Ordinal) >= 0)
929 if ((style & DateTimeStyles.AllowLeadingWhite) != 0) {
930 format = format.TrimStart (null);
932 s = s.TrimStart (null); // it could be optimized, but will make little good.
935 if ((style & DateTimeStyles.AllowTrailingWhite) != 0) {
936 format = format.TrimEnd (null);
937 s = s.TrimEnd (null); // it could be optimized, but will make little good.
941 dfi = DateTimeFormatInfo.InvariantInfo;
943 if ((style & DateTimeStyles.AllowInnerWhite) != 0)
944 sloppy_parsing = true;
946 string chars = format;
947 int len = format.Length, pos = 0, num = 0;
949 int day = -1, dayofweek = -1, month = -1, year = -1;
950 int hour = -1, minute = -1, second = -1;
951 double fractionalSeconds = -1;
953 int tzsign = -1, tzoffset = -1, tzoffmin = -1;
955 result = new DateTime (0);
956 while (pos+num < len)
958 if (s.Length == valuePos)
961 if (chars[pos] == '\'') {
963 while (pos+num < len) {
964 if (chars[pos+num] == '\'')
967 if (valuePos == s.Length)
969 if (s [valuePos] != chars [pos + num])
981 } else if (chars[pos] == '"') {
983 while (pos+num < len) {
984 if (chars[pos+num] == '"')
987 if (valuePos == s.Length)
989 if (s [valuePos] != chars[pos+num])
1001 } else if (chars[pos] == '\\') {
1007 if (s [valuePos] != chars [pos])
1012 } else if (chars[pos] == '%') {
1015 } else if (Char.IsWhiteSpace (s [valuePos]) ||
1016 s [valuePos] == ',' && Char.IsWhiteSpace (chars [pos])) {
1019 if (exact && (style & DateTimeStyles.AllowInnerWhite) == 0) {
1020 if (!Char.IsWhiteSpace (chars[pos]))
1027 while (ws < s.Length) {
1028 if (Char.IsWhiteSpace (s [ws]) || s [ws] == ',')
1035 while (ws < chars.Length) {
1036 if (Char.IsWhiteSpace (chars [ws]) || chars [ws] == ',')
1045 if ((pos+num+1 < len) && (chars[pos+num+1] == chars[pos+num])) {
1059 day = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1061 day = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1063 dayofweek = _ParseEnum (s, valuePos, dfi.RawAbbreviatedDayNames, out num_parsed);
1066 dayofweek = _ParseEnum (s, valuePos, dfi.RawDayNames, out num_parsed);
1074 month = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1076 month = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1078 month = _ParseEnum (s, valuePos, dfi.RawAbbreviatedMonthNames , out num_parsed) + 1;
1081 month = _ParseEnum (s, valuePos, dfi.RawMonthNames, out num_parsed) + 1;
1090 year = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1091 } else if (num < 3) {
1092 year = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1094 year = _ParseNumber (s, valuePos,4, 4, false, sloppy_parsing, out num_parsed);
1095 if ((year >= 1000) && (num_parsed == 4) && (!longYear) && (s.Length > 4 + valuePos)) {
1097 int ly = _ParseNumber (s, valuePos, 5, 5, false, sloppy_parsing, out np);
1098 longYear = (ly > 9999);
1103 //FIXME: We should do use dfi.Calendat.TwoDigitYearMax
1104 if (num_parsed <= 2)
1105 year += (year < 30) ? 2000 : 1900;
1111 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1114 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1125 if ((hour != -1) || (ampm >= 0))
1128 hour = _ParseNumber (s, valuePos,0, 2, false, sloppy_parsing, out num_parsed);
1131 hour = _ParseNumber (s, valuePos,0, 2, true, sloppy_parsing, out num_parsed);
1143 minute = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1146 minute = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1157 second = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1160 second = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1168 if (fractionalSeconds != -1)
1170 num = Math.Min (num, 6);
1171 double decimalNumber = (double) _ParseNumber (s, valuePos, 0, num+1, true, sloppy_parsing, out num_parsed);
1172 if (num_parsed == -1)
1176 fractionalSeconds = decimalNumber / Math.Pow(10.0, num_parsed);
1183 if (_ParseString (s, valuePos, 1, dfi.AMDesignator, out num_parsed))
1185 else if (_ParseString (s, valuePos, 1, dfi.PMDesignator, out num_parsed))
1192 if (_ParseString (s, valuePos, 0, dfi.AMDesignator, out num_parsed))
1194 else if (_ParseString (s, valuePos, 0, dfi.PMDesignator, out num_parsed))
1204 if (s [valuePos] == '+')
1206 else if (s [valuePos] == '-')
1212 tzoffset = _ParseNumber (s, valuePos, 0, 2, false, sloppy_parsing, out num_parsed);
1214 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1217 tzoffset = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1220 valuePos += num_parsed;
1221 if (Char.IsDigit (s [valuePos]))
1223 else if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1225 valuePos += num_parsed;
1226 tzoffmin = _ParseNumber (s, valuePos, 0, 2, true, sloppy_parsing, out num_parsed);
1233 // LAMESPEC: This should be part of UTCpattern
1234 // string and thus should not be considered here.
1236 // Note that 'Z' is not defined as a pattern
1237 // character. Keep it for X509 certificate
1238 // verification. Also, "Z" != "'Z'" under MS.NET
1239 // ("'Z'" is just literal; handled above)
1241 if (s [valuePos] != 'Z')
1249 if (!_ParseString (s, valuePos, 0, dfi.TimeSeparator, out num_parsed))
1253 /* Accept any character for
1254 * DateSeparator, except
1255 * TimeSeparator, a digit or a
1256 * letter. Not documented,
1257 * but seems to be MS
1258 * behaviour here. See bug
1261 if (exact && s [valuePos] != '/')
1264 if (_ParseString (s, valuePos, 0,
1267 Char.IsDigit (s [valuePos]) ||
1268 Char.IsLetter (s [valuePos])) {
1273 if (num_parsed <= 0) {
1279 if (s [valuePos] != chars[pos]) {
1280 // FIXME: It is not sure, but
1281 // IsLetter() is introduced
1282 // because we have to reject
1283 // "2002a02b25" but have to
1284 // allow "2002$02$25". The same
1285 // thing applies to '/' case.
1287 Char.IsDigit (s [valuePos]) ||
1288 Char.IsLetter (s [valuePos]))
1299 valuePos += num_parsed;
1302 switch (chars [pos]) {
1307 if (s.Length > valuePos && s [valuePos] == 'Z'
1308 && (pos + 1 == chars.Length
1309 || chars [pos + 1] != 'Z')) {
1317 pos = pos + num + 1;
1321 // possible empty value. Regarded as no match.
1328 if (s.Length != valuePos) // extraneous tail.
1338 if (fractionalSeconds == -1)
1339 fractionalSeconds = 0;
1341 // If no date was given
1342 if ((day == -1) && (month == -1) && (year == -1)) {
1343 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
1349 month = Today.Month;
1360 if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
1369 // For anything out of range
1371 if ( year < 1 || year > 9999 ||
1372 month < 1 || month >12 ||
1373 day < 1 || day > DaysInMonth(year, month) ||
1374 hour < 0 || hour > 23 ||
1375 minute < 0 || minute > 59 ||
1376 second < 0 || second > 59 )
1379 result = new DateTime (year, month, day, hour, minute, second, 0);
1380 result = result.AddSeconds(fractionalSeconds);
1382 if ((dayofweek != -1) && (dayofweek != (int) result.DayOfWeek))
1383 throw new FormatException (Locale.GetText ("String was not recognized as valid DateTime because the day of week was incorrect."));
1385 // If no timezone was specified, default to the local timezone.
1389 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1390 use_localtime = false;
1391 utcoffset = new TimeSpan (0, 0, 0);
1392 } else if (tzsign == -1) {
1393 TimeZone tz = TimeZone.CurrentTimeZone;
1394 utcoffset = tz.GetUtcOffset (result);
1396 if ((style & DateTimeStyles.AdjustToUniversal) != 0)
1397 use_localtime = false;
1404 tzoffset = -tzoffset
1406 utcoffset = new TimeSpan (tzoffset, tzoffmin, 0);
1409 long newticks = (result.ticks - utcoffset).Ticks;
1411 result = new DateTime (false, new TimeSpan (newticks));
1413 result = result.ToLocalTime ();
1419 public static DateTime ParseExact (string s, string format,
1420 IFormatProvider fp, DateTimeStyles style)
1424 formats = new string [1];
1425 formats[0] = format;
1427 return ParseExact (s, formats, fp, style);
1430 public static DateTime ParseExact (string s, string[] formats,
1432 DateTimeStyles style)
1434 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1437 throw new ArgumentNullException (Locale.GetText ("s is null"));
1438 if (formats == null || formats.Length == 0)
1439 throw new ArgumentNullException (Locale.GetText ("format is null"));
1442 bool longYear = false;
1443 if (!ParseExact (s, formats, dfi, style, out result, true, ref longYear))
1444 throw new FormatException ();
1449 public static bool TryParse (string s, out DateTime result)
1460 public static bool TryParse (string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result)
1463 result = Parse (s, provider, styles);
1471 public static bool TryParseExact (string s, string format,
1473 DateTimeStyles style,
1474 out DateTime result)
1478 formats = new string [1];
1479 formats[0] = format;
1481 return TryParseExact (s, formats, fp, style, out result);
1484 public static bool TryParseExact (string s, string[] formats,
1486 DateTimeStyles style,
1487 out DateTime result)
1489 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance (fp);
1491 bool longYear = false;
1492 return ParseExact (s, formats, dfi, style, out result, true, ref longYear);
1496 private static bool ParseExact (string s, string [] formats,
1497 DateTimeFormatInfo dfi, DateTimeStyles style, out DateTime ret,
1498 bool exact, ref bool longYear)
1501 for (i = 0; i < formats.Length; i++)
1505 if (_DoParse (s, formats[i], exact, out result, dfi, style, ref longYear)) {
1510 ret = DateTime.MinValue;
1514 public TimeSpan Subtract(DateTime dt)
1516 return new TimeSpan(ticks.Ticks) - dt.ticks;
1519 public DateTime Subtract(TimeSpan ts)
1523 newticks = (new TimeSpan (ticks.Ticks)) - ts;
1524 return new DateTime(true,newticks);
1527 public long ToFileTime()
1529 DateTime universalTime = ToUniversalTime();
1531 if (universalTime.Ticks < w32file_epoch) {
1532 throw new ArgumentOutOfRangeException("file time is not valid");
1535 return(universalTime.Ticks - w32file_epoch);
1539 public long ToFileTimeUtc()
1541 if (Ticks < w32file_epoch) {
1542 throw new ArgumentOutOfRangeException("file time is not valid");
1545 return (Ticks - w32file_epoch);
1549 public string ToLongDateString()
1551 return ToString ("D");
1554 public string ToLongTimeString()
1556 return ToString ("T");
1559 public double ToOADate ()
1561 long t = this.Ticks;
1562 // uninitialized DateTime case
1565 // we can't reach minimum value
1566 if (t < 31242239136000000)
1567 return OAMinValue + 0.001;
1569 TimeSpan ts = new TimeSpan (this.Ticks - ticks18991230);
1570 double result = ts.TotalDays;
1571 // t < 0 (where 599264352000000000 == 0.0d for OA)
1572 if (t < 599264352000000000) {
1573 // negative days (int) but decimals are positive
1574 double d = Math.Ceiling (result);
1575 result = d - 2 - (result - d);
1578 // we can't reach maximum value
1579 if (result >= OAMaxValue)
1580 result = OAMaxValue - 0.00000001d;
1585 public string ToShortDateString()
1587 return ToString ("d");
1590 public string ToShortTimeString()
1592 return ToString ("t");
1595 public override string ToString ()
1597 return ToString ("G", null);
1600 public string ToString (IFormatProvider fp)
1602 return ToString (null, fp);
1605 public string ToString (string format)
1607 return ToString (format, null);
1610 internal static string _GetStandardPattern (char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant)
1615 use_invariant = false;
1620 pattern = dfi.ShortDatePattern;
1623 pattern = dfi.LongDatePattern;
1626 pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
1629 pattern = dfi.FullDateTimePattern;
1632 pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
1635 pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
1639 pattern = dfi.MonthDayPattern;
1643 pattern = dfi.RFC1123Pattern;
1644 // commented by LP 09/jun/2002, rfc 1123 pattern is always in GMT
1645 // uncommented by AE 27/may/2004
1647 use_invariant = true;
1650 pattern = dfi.SortableDateTimePattern;
1653 pattern = dfi.ShortTimePattern;
1656 pattern = dfi.LongTimePattern;
1659 pattern = dfi.UniversalSortableDateTimePattern;
1663 // pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
1664 pattern = dfi.FullDateTimePattern;
1669 pattern = dfi.YearMonthPattern;
1679 internal string _ToString (string format, DateTimeFormatInfo dfi)
1681 // the length of the format is usually a good guess of the number
1682 // of chars in the result. Might save us a few bytes sometimes
1683 // Add + 10 for cases like mmmm dddd
1684 StringBuilder result = new StringBuilder (format.Length + 10);
1686 // For some cases, the output should not use culture dependent calendar
1687 DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo;
1688 if (format == inv.RFC1123Pattern)
1690 else if (format == inv.UniversalSortableDateTimePattern)
1695 while (i < format.Length) {
1697 char ch = format [i];
1706 tokLen = CountRepeat (format, i, ch);
1708 int hr = this.Hour % 12;
1712 ZeroPad (result, hr, tokLen == 1 ? 1 : 2);
1716 tokLen = CountRepeat (format, i, ch);
1717 ZeroPad (result, this.Hour, tokLen == 1 ? 1 : 2);
1721 tokLen = CountRepeat (format, i, ch);
1722 ZeroPad (result, this.Minute, tokLen == 1 ? 1 : 2);
1726 tokLen = CountRepeat (format, i, ch);
1727 ZeroPad (result, this.Second, tokLen == 1 ? 1 : 2);
1730 // fraction of second, to same number of
1731 // digits as there are f's
1733 tokLen = CountRepeat (format, i, ch);
1735 throw new FormatException ("Invalid Format String");
1737 int dec = (int)((long)(this.Ticks % TimeSpan.TicksPerSecond) / (long) Math.Pow (10, 7 - tokLen));
1738 ZeroPad (result, dec, tokLen);
1742 // AM/PM. t == first char, tt+ == full
1743 tokLen = CountRepeat (format, i, ch);
1744 string desig = this.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator;
1747 if (desig.Length >= 1)
1748 result.Append (desig [0]);
1751 result.Append (desig);
1755 // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm
1756 tokLen = CountRepeat (format, i, ch);
1757 TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset (this);
1759 if (offset.Ticks >= 0)
1760 result.Append ('+');
1762 result.Append ('-');
1766 result.Append (Math.Abs (offset.Hours));
1769 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1772 result.Append (Math.Abs (offset.Hours).ToString ("00"));
1773 result.Append (':');
1774 result.Append (Math.Abs (offset.Minutes).ToString ("00"));
1782 // day. d(d?) = day of month (leading 0 if two d's)
1783 // ddd = three leter day of week
1784 // dddd+ full day-of-week
1785 tokLen = CountRepeat (format, i, ch);
1788 ZeroPad (result, dfi.Calendar.GetDayOfMonth (this), tokLen == 1 ? 1 : 2);
1789 else if (tokLen == 3)
1790 result.Append (dfi.GetAbbreviatedDayName (dfi.Calendar.GetDayOfWeek (this)));
1792 result.Append (dfi.GetDayName (dfi.Calendar.GetDayOfWeek (this)));
1796 // Month.m(m?) = month # (with leading 0 if two mm)
1797 // mmm = 3 letter name
1798 // mmmm+ = full name
1799 tokLen = CountRepeat (format, i, ch);
1800 int month = dfi.Calendar.GetMonth(this);
1802 ZeroPad (result, month, tokLen);
1803 else if (tokLen == 3)
1804 result.Append (dfi.GetAbbreviatedMonthName (month));
1806 result.Append (dfi.GetMonthName (month));
1810 // Year. y(y?) = two digit year, with leading 0 if yy
1811 // yyy+ full year, if yyy and yr < 1000, displayed as three digits
1812 tokLen = CountRepeat (format, i, ch);
1815 ZeroPad (result, dfi.Calendar.GetYear (this) % 100, tokLen);
1817 ZeroPad (result, dfi.Calendar.GetYear (this), (tokLen == 3 ? 3 : 4));
1822 tokLen = CountRepeat (format, i, ch);
1823 result.Append (dfi.GetEraName (dfi.Calendar.GetEra (this)));
1830 result.Append (dfi.TimeSeparator);
1834 result.Append (dfi.DateSeparator);
1837 case '\'': case '"':
1838 tokLen = ParseQuotedString (format, i, result);
1841 if (i >= format.Length - 1)
1842 throw new FormatException ("% at end of date time string");
1843 if (format [i + 1] == '%')
1844 throw new FormatException ("%% in date string");
1846 // Look for the next char
1851 if (i >= format.Length - 1)
1852 throw new FormatException ("\\ at end of date time string");
1854 result.Append (format [i + 1]);
1866 return result.ToString ();
1869 static int CountRepeat (string fmt, int p, char c)
1873 while ((i < l) && (fmt [i] == c))
1879 static int ParseQuotedString (string fmt, int pos, StringBuilder output)
1881 // pos == position of " or '
1883 int len = fmt.Length;
1885 char quoteChar = fmt [pos++];
1888 char ch = fmt [pos++];
1890 if (ch == quoteChar)
1896 throw new FormatException("Un-ended quote");
1898 output.Append (fmt [pos++]);
1904 throw new FormatException("Un-ended quote");
1907 static unsafe void ZeroPad (StringBuilder output, int digits, int len)
1909 // more than enough for an int
1910 char* buffer = stackalloc char [16];
1914 buffer [-- pos] = (char) ('0' + digits % 10);
1917 } while (digits > 0);
1920 buffer [-- pos] = '0';
1922 output.Append (new string (buffer, pos, 16 - pos));
1925 public string ToString (string format, IFormatProvider fp)
1928 DateTimeFormatInfo dfi = DateTimeFormatInfo.GetInstance(fp);
1933 bool useutc = false, use_invariant = false;
1935 if (format.Length == 1) {
1936 char fchar = format [0];
1937 format = _GetStandardPattern (fchar, dfi, out useutc, out use_invariant);
1940 // Don't convert UTC value. It just adds 'Z' for
1941 // 'u' format, for the same ticks.
1942 return this._ToString (format, dfi);
1945 public DateTime ToLocalTime ()
1947 return TimeZone.CurrentTimeZone.ToLocalTime (this);
1950 public DateTime ToUniversalTime()
1952 return TimeZone.CurrentTimeZone.ToUniversalTime (this);
1957 public static DateTime operator +(DateTime d, TimeSpan t)
1959 return new DateTime (true, d.ticks + t);
1962 public static bool operator ==(DateTime d1, DateTime d2)
1964 return (d1.ticks == d2.ticks);
1967 public static bool operator >(DateTime t1,DateTime t2)
1969 return (t1.ticks > t2.ticks);
1972 public static bool operator >=(DateTime t1,DateTime t2)
1974 return (t1.ticks >= t2.ticks);
1977 public static bool operator !=(DateTime d1, DateTime d2)
1979 return (d1.ticks != d2.ticks);
1982 public static bool operator <(DateTime t1, DateTime t2)
1984 return (t1.ticks < t2.ticks );
1987 public static bool operator <=(DateTime t1,DateTime t2)
1989 return (t1.ticks <= t2.ticks);
1992 public static TimeSpan operator -(DateTime d1,DateTime d2)
1994 return new TimeSpan((d1.ticks - d2.ticks).Ticks);
1997 public static DateTime operator -(DateTime d,TimeSpan t)
1999 return new DateTime (true, d.ticks - t);
2002 bool IConvertible.ToBoolean(IFormatProvider provider)
2004 throw new InvalidCastException();
2007 byte IConvertible.ToByte(IFormatProvider provider)
2009 throw new InvalidCastException();
2013 char IConvertible.ToChar(IFormatProvider provider)
2015 throw new InvalidCastException();
2018 System.DateTime IConvertible.ToDateTime(IFormatProvider provider)
2023 decimal IConvertible.ToDecimal(IFormatProvider provider)
2025 throw new InvalidCastException();
2028 double IConvertible.ToDouble(IFormatProvider provider)
2030 throw new InvalidCastException();
2033 Int16 IConvertible.ToInt16(IFormatProvider provider)
2035 throw new InvalidCastException();
2038 Int32 IConvertible.ToInt32(IFormatProvider provider)
2040 throw new InvalidCastException();
2043 Int64 IConvertible.ToInt64(IFormatProvider provider)
2045 throw new InvalidCastException();
2048 SByte IConvertible.ToSByte(IFormatProvider provider)
2050 throw new InvalidCastException();
2053 Single IConvertible.ToSingle(IFormatProvider provider)
2055 throw new InvalidCastException();
2058 object IConvertible.ToType (Type conversionType, IFormatProvider provider)
2060 if (conversionType == null)
2061 throw new ArgumentNullException ("conversionType");
2063 if (conversionType == typeof (DateTime))
2065 else if (conversionType == typeof (String))
2066 return this.ToString (provider);
2067 else if (conversionType == typeof (Object))
2070 throw new InvalidCastException();
2073 UInt16 IConvertible.ToUInt16(IFormatProvider provider)
2075 throw new InvalidCastException();
2078 UInt32 IConvertible.ToUInt32(IFormatProvider provider)
2080 throw new InvalidCastException();
2083 UInt64 IConvertible.ToUInt64(IFormatProvider provider)
2085 throw new InvalidCastException();