5 // Duco Fijma (duco@lorentz.xs4all.nl)
6 // Andreas Nahr (ClassDevelopment@A-SoftTech.com)
7 // Sebastien Pouliot <sebastien@ximian.com>
10 // (C) 2004 Andreas Nahr
11 // Copyright (C) 2004 Novell (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 [System.Runtime.InteropServices.ComVisible (true)]
41 public struct TimeSpan : IComparable
43 , IComparable<TimeSpan>, IEquatable <TimeSpan>
46 public static readonly TimeSpan MaxValue = new TimeSpan (long.MaxValue);
47 public static readonly TimeSpan MinValue = new TimeSpan (long.MinValue);
48 public static readonly TimeSpan Zero = new TimeSpan (0L);
50 public const long TicksPerDay = 864000000000L;
51 public const long TicksPerHour = 36000000000L;
52 public const long TicksPerMillisecond = 10000L;
53 public const long TicksPerMinute = 600000000L;
54 public const long TicksPerSecond = 10000000L;
58 public TimeSpan (long value)
63 public TimeSpan (int hours, int minutes, int seconds)
65 _ticks = CalculateTicks (0, hours, minutes, seconds, 0);
68 public TimeSpan (int days, int hours, int minutes, int seconds)
70 _ticks = CalculateTicks (days, hours, minutes, seconds, 0);
73 public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds)
75 _ticks = CalculateTicks (days, hours, minutes, seconds, milliseconds);
78 internal static long CalculateTicks (int days, int hours, int minutes, int seconds, int milliseconds)
80 // there's no overflow checks for hours, minutes, ...
81 // so big hours/minutes values can overflow at some point and change expected values
82 int hrssec = (hours * 3600); // break point at (Int32.MaxValue - 596523)
83 int minsec = (minutes * 60);
84 long t = ((long)(hrssec + minsec + seconds) * 1000L + (long)milliseconds);
87 bool overflow = false;
88 // days is problematic because it can overflow but that overflow can be
89 // "legal" (i.e. temporary) (e.g. if other parameters are negative) or
90 // illegal (e.g. sign change).
92 long td = TicksPerDay * days;
96 // positive days -> total ticks should be lower
97 overflow = (ticks > t);
101 // positive + positive != negative result
106 long td = TicksPerDay * days;
109 // negative + negative != positive result
115 // negative days -> total ticks should be lower
116 overflow = (t > ticks);
121 throw new ArgumentOutOfRangeException (Locale.GetText ("The timespan is too big or too small."));
128 return (int) (_ticks / TicksPerDay);
134 return (int) (_ticks % TicksPerDay / TicksPerHour);
138 public int Milliseconds {
140 return (int) (_ticks % TicksPerSecond / TicksPerMillisecond);
146 return (int) (_ticks % TicksPerHour / TicksPerMinute);
152 return (int) (_ticks % TicksPerMinute / TicksPerSecond);
162 public double TotalDays {
164 return (double) _ticks / TicksPerDay;
168 public double TotalHours {
170 return (double) _ticks / TicksPerHour;
174 public double TotalMilliseconds {
176 return (double) _ticks / TicksPerMillisecond;
180 public double TotalMinutes {
182 return (double) _ticks / TicksPerMinute;
186 public double TotalSeconds {
188 return (double) _ticks / TicksPerSecond;
192 public TimeSpan Add (TimeSpan ts)
196 return new TimeSpan (_ticks + ts.Ticks);
199 catch (OverflowException) {
200 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
204 public static int Compare (TimeSpan t1, TimeSpan t2)
206 if (t1._ticks < t2._ticks)
208 if (t1._ticks > t2._ticks)
213 public int CompareTo (object value)
218 if (!(value is TimeSpan)) {
219 throw new ArgumentException (Locale.GetText ("Argument has to be a TimeSpan."), "value");
222 return Compare (this, (TimeSpan) value);
226 public int CompareTo (TimeSpan value)
228 return Compare (this, value);
231 public bool Equals (TimeSpan value)
233 return value._ticks == _ticks;
237 public TimeSpan Duration ()
241 return new TimeSpan (Math.Abs (_ticks));
244 catch (OverflowException) {
245 throw new OverflowException (Locale.GetText (
246 "This TimeSpan value is MinValue so you cannot get the duration."));
250 public override bool Equals (object value)
252 if (!(value is TimeSpan))
255 return _ticks == ((TimeSpan) value)._ticks;
258 public static bool Equals (TimeSpan t1, TimeSpan t2)
260 return t1._ticks == t2._ticks;
263 public static TimeSpan FromDays (double value)
265 return From (value, TicksPerDay);
268 public static TimeSpan FromHours (double value)
270 return From (value, TicksPerHour);
273 public static TimeSpan FromMinutes (double value)
275 return From (value, TicksPerMinute);
278 public static TimeSpan FromSeconds (double value)
280 return From (value, TicksPerSecond);
283 public static TimeSpan FromMilliseconds (double value)
285 return From (value, TicksPerMillisecond);
288 private static TimeSpan From (double value, long tickMultiplicator)
290 if (Double.IsNaN (value))
291 throw new ArgumentException (Locale.GetText ("Value cannot be NaN."), "value");
292 if (Double.IsNegativeInfinity (value) || Double.IsPositiveInfinity (value) ||
293 (value < MinValue.Ticks) || (value > MaxValue.Ticks))
294 throw new OverflowException (Locale.GetText ("Outside range [MinValue,MaxValue]"));
297 value = (value * (tickMultiplicator / TicksPerMillisecond));
300 long val = (long) Math.Round(value);
301 return new TimeSpan (val * TicksPerMillisecond);
304 catch (OverflowException) {
305 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
309 public static TimeSpan FromTicks (long value)
311 return new TimeSpan (value);
314 public override int GetHashCode ()
316 return _ticks.GetHashCode ();
319 public TimeSpan Negate ()
321 if (_ticks == MinValue._ticks)
322 throw new OverflowException (Locale.GetText (
323 "This TimeSpan value is MinValue and cannot be negated."));
324 return new TimeSpan (-_ticks);
327 public static TimeSpan Parse (string s)
330 throw new ArgumentNullException ("s");
333 Parser p = new Parser (s);
338 public static bool TryParse (string s, out TimeSpan result)
344 result = TimeSpan.Zero;
350 public TimeSpan Subtract (TimeSpan ts)
354 return new TimeSpan (_ticks - ts.Ticks);
357 catch (OverflowException) {
358 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
362 public override string ToString ()
364 StringBuilder sb = new StringBuilder (14);
369 // We need to take absolute values of all components.
370 // Can't handle negative timespans by negating the TimeSpan
371 // as a whole. This would lead to an overflow for the
372 // degenerate case "TimeSpan.MinValue.ToString()".
374 sb.Append (Math.Abs (Days));
378 System.Globalization.NumberFormatInfo nfi = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
379 sb.Append (new NumberFormatter (null, (int)Math.Abs (Hours)).FormatDecimal(2, nfi));
381 sb.Append (new NumberFormatter (null, (int)Math.Abs (Minutes)).FormatDecimal(2, nfi));
383 sb.Append (new NumberFormatter (null, (int)Math.Abs (Seconds)).FormatDecimal(2, nfi));
385 int fractional = (int) Math.Abs (_ticks % TicksPerSecond);
386 if (fractional != 0) {
388 sb.Append (new NumberFormatter (null, (int)Math.Abs (fractional)).FormatDecimal(7, nfi));
391 return sb.ToString ();
394 public static TimeSpan operator + (TimeSpan t1, TimeSpan t2)
399 public static bool operator == (TimeSpan t1, TimeSpan t2)
401 return t1._ticks == t2._ticks;
404 public static bool operator > (TimeSpan t1, TimeSpan t2)
406 return t1._ticks > t2._ticks;
409 public static bool operator >= (TimeSpan t1, TimeSpan t2)
411 return t1._ticks >= t2._ticks;
414 public static bool operator != (TimeSpan t1, TimeSpan t2)
416 return t1._ticks != t2._ticks;
419 public static bool operator < (TimeSpan t1, TimeSpan t2)
421 return t1._ticks < t2._ticks;
424 public static bool operator <= (TimeSpan t1, TimeSpan t2)
426 return t1._ticks <= t2._ticks;
429 public static TimeSpan operator - (TimeSpan t1, TimeSpan t2)
431 return t1.Subtract (t2);
434 public static TimeSpan operator - (TimeSpan t)
439 public static TimeSpan operator + (TimeSpan t)
444 // Class Parser implements parser for TimeSpan.Parse
448 private int _cur = 0;
450 private bool formatError;
452 public Parser (string src)
455 _length = _src.Length;
460 return _cur >= _length;
464 // All "Parse" functions throw a FormatException on syntax error.
465 // Their return value is semantic value of the item parsed.
467 // Range checking is spread over three different places:
468 // 1) When parsing "int" values, an exception is thrown immediately
469 // when the value parsed exceeds the maximum value for an int.
470 // 2) An explicit check is built in that checks for hours > 23 and
471 // for minutes and seconds > 59.
472 // 3) Throwing an exceptions for a final TimeSpan value > MaxValue
473 // or < MinValue is left to the TimeSpan constructor called.
475 // Parse zero or more whitespace chars.
476 private void ParseWhiteSpace ()
478 while (!AtEnd && Char.IsWhiteSpace (_src, _cur)) {
483 // Parse optional sign character.
484 private bool ParseSign ()
488 if (!AtEnd && _src[_cur] == '-') {
496 // Parse simple int value
497 private int ParseInt (bool optional)
499 if (optional && AtEnd)
505 while (!AtEnd && Char.IsDigit (_src, _cur)) {
507 res = res * 10 + _src[_cur] - '0';
519 // Parse optional dot
520 private bool ParseOptDot ()
525 if (_src[_cur] == '.') {
532 // Parse optional (LAMESPEC) colon
533 private void ParseOptColon ()
536 if (_src[_cur] == ':')
543 // Parse [1..7] digits, representing fractional seconds (ticks)
544 private long ParseTicks ()
548 bool digitseen = false;
550 while (mag > 0 && !AtEnd && Char.IsDigit (_src, _cur)) {
551 res = res + (_src[_cur] - '0') * mag;
563 public TimeSpan Execute ()
573 // Parse [ws][-][dd.]hh:mm:ss[.ff][ws]
574 // ... but not entirely true as an lonely
575 // integer will be parsed as a number of days
578 days = ParseInt (false);
579 if (ParseOptDot ()) {
580 hours = ParseInt (true);
587 minutes = ParseInt (true);
589 seconds = ParseInt (true);
590 if ( ParseOptDot () ) {
591 ticks = ParseTicks ();
601 // Overflow has presceance over FormatException
602 if (hours > 23 || minutes > 59 || seconds > 59) {
603 throw new OverflowException (
604 Locale.GetText ("Invalid time data."));
606 else if (formatError) {
607 throw new FormatException (
608 Locale.GetText ("Invalid format for TimeSpan.Parse."));
611 long t = TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0);
612 t = checked ((sign) ? (-t - ticks) : (t + ticks));
613 return new TimeSpan (t);