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.
38 public struct TimeSpan : IComparable
40 , IComparable<TimeSpan>, IEquatable <TimeSpan>
43 public static readonly TimeSpan MaxValue = new TimeSpan (long.MaxValue);
44 public static readonly TimeSpan MinValue = new TimeSpan (long.MinValue);
45 public static readonly TimeSpan Zero = new TimeSpan (0L);
47 public const long TicksPerDay = 864000000000L;
48 public const long TicksPerHour = 36000000000L;
49 public const long TicksPerMillisecond = 10000L;
50 public const long TicksPerMinute = 600000000L;
51 public const long TicksPerSecond = 10000000L;
55 public TimeSpan (long value)
60 public TimeSpan (int hours, int minutes, int seconds)
62 _ticks = CalculateTicks (0, hours, minutes, seconds, 0);
65 public TimeSpan (int days, int hours, int minutes, int seconds)
67 _ticks = CalculateTicks (days, hours, minutes, seconds, 0);
70 public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds)
72 _ticks = CalculateTicks (days, hours, minutes, seconds, milliseconds);
75 internal static long CalculateTicks (int days, int hours, int minutes, int seconds, int milliseconds)
77 // there's no overflow checks for hours, minutes, ...
78 // so big hours/minutes values can overflow at some point and change expected values
79 int hrssec = (hours * 3600); // break point at (Int32.MaxValue - 596523)
80 int minsec = (minutes * 60);
81 long t = ((long)(hrssec + minsec + seconds) * 1000L + (long)milliseconds);
84 bool overflow = false;
85 // days is problematic because it can overflow but that overflow can be
86 // "legal" (i.e. temporary) (e.g. if other parameters are negative) or
87 // illegal (e.g. sign change).
89 long td = TicksPerDay * days;
93 // positive days -> total ticks should be lower
94 overflow = (ticks > t);
98 // positive + positive != negative result
103 long td = TicksPerDay * days;
106 // negative + negative != positive result
112 // negative days -> total ticks should be lower
113 overflow = (t > ticks);
118 throw new ArgumentOutOfRangeException (Locale.GetText ("The timespan is too big or too small."));
125 return (int) (_ticks / TicksPerDay);
131 return (int) (_ticks % TicksPerDay / TicksPerHour);
135 public int Milliseconds {
137 return (int) (_ticks % TicksPerSecond / TicksPerMillisecond);
143 return (int) (_ticks % TicksPerHour / TicksPerMinute);
149 return (int) (_ticks % TicksPerMinute / TicksPerSecond);
159 public double TotalDays {
161 return (double) _ticks / TicksPerDay;
165 public double TotalHours {
167 return (double) _ticks / TicksPerHour;
171 public double TotalMilliseconds {
173 return (double) _ticks / TicksPerMillisecond;
177 public double TotalMinutes {
179 return (double) _ticks / TicksPerMinute;
183 public double TotalSeconds {
185 return (double) _ticks / TicksPerSecond;
189 public TimeSpan Add (TimeSpan ts)
193 return new TimeSpan (_ticks + ts.Ticks);
196 catch (OverflowException) {
197 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
201 public static int Compare (TimeSpan t1, TimeSpan t2)
203 if (t1._ticks < t2._ticks)
205 if (t1._ticks > t2._ticks)
210 public int CompareTo (object value)
215 if (!(value is TimeSpan)) {
216 throw new ArgumentException (Locale.GetText ("Argument has to be a TimeSpan."), "value");
219 return Compare (this, (TimeSpan) value);
223 public int CompareTo (TimeSpan value)
225 return Compare (this, value);
228 public bool Equals (TimeSpan value)
230 return value._ticks == _ticks;
234 public TimeSpan Duration ()
238 return new TimeSpan (Math.Abs (_ticks));
241 catch (OverflowException) {
242 throw new OverflowException (Locale.GetText (
243 "This TimeSpan value is MinValue so you cannot get the duration."));
247 public override bool Equals (object value)
249 if (!(value is TimeSpan))
252 return _ticks == ((TimeSpan) value)._ticks;
255 public static bool Equals (TimeSpan t1, TimeSpan t2)
257 return t1._ticks == t2._ticks;
260 public static TimeSpan FromDays (double value)
262 return From (value, TicksPerDay);
265 public static TimeSpan FromHours (double value)
267 return From (value, TicksPerHour);
270 public static TimeSpan FromMinutes (double value)
272 return From (value, TicksPerMinute);
275 public static TimeSpan FromSeconds (double value)
277 return From (value, TicksPerSecond);
280 public static TimeSpan FromMilliseconds (double value)
282 return From (value, TicksPerMillisecond);
285 private static TimeSpan From (double value, long tickMultiplicator)
287 if (Double.IsNaN (value))
288 throw new ArgumentException (Locale.GetText ("Value cannot be NaN."), "value");
289 if (Double.IsNegativeInfinity (value) || Double.IsPositiveInfinity (value) ||
290 (value < MinValue.Ticks) || (value > MaxValue.Ticks))
291 throw new OverflowException (Locale.GetText ("Outside range [MinValue,MaxValue]"));
294 value = (value * (tickMultiplicator / TicksPerMillisecond));
297 long val = (long) Math.Round(value);
298 return new TimeSpan (val * TicksPerMillisecond);
301 catch (OverflowException) {
302 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
306 public static TimeSpan FromTicks (long value)
308 return new TimeSpan (value);
311 public override int GetHashCode ()
313 return _ticks.GetHashCode ();
316 public TimeSpan Negate ()
318 if (_ticks == MinValue._ticks)
319 throw new OverflowException (Locale.GetText (
320 "This TimeSpan value is MinValue and cannot be negated."));
321 return new TimeSpan (-_ticks);
324 public static TimeSpan Parse (string s)
327 throw new ArgumentNullException ("s");
330 Parser p = new Parser (s);
335 public static bool TryParse (string s, out TimeSpan result)
341 result = TimeSpan.Zero;
347 public TimeSpan Subtract (TimeSpan ts)
351 return new TimeSpan (_ticks - ts.Ticks);
354 catch (OverflowException) {
355 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
359 public override string ToString ()
361 StringBuilder sb = new StringBuilder (14);
366 // We need to take absolute values of all components.
367 // Can't handle negative timespans by negating the TimeSpan
368 // as a whole. This would lead to an overflow for the
369 // degenerate case "TimeSpan.MinValue.ToString()".
371 sb.Append (Math.Abs (Days));
375 System.Globalization.NumberFormatInfo nfi = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
376 sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore ((int)Math.Abs (Hours)), 2, nfi));
378 sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore ((int)Math.Abs (Minutes)), 2, nfi));
380 sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore ((int)Math.Abs (Seconds)), 2, nfi));
382 int fractional = (int) Math.Abs (_ticks % TicksPerSecond);
383 if (fractional != 0) {
385 sb.Append (NumberFormatter.FormatDecimal (new NumberFormatter.NumberStore (fractional), 7, nfi));
388 return sb.ToString ();
391 public static TimeSpan operator + (TimeSpan t1, TimeSpan t2)
396 public static bool operator == (TimeSpan t1, TimeSpan t2)
398 return t1._ticks == t2._ticks;
401 public static bool operator > (TimeSpan t1, TimeSpan t2)
403 return t1._ticks > t2._ticks;
406 public static bool operator >= (TimeSpan t1, TimeSpan t2)
408 return t1._ticks >= t2._ticks;
411 public static bool operator != (TimeSpan t1, TimeSpan t2)
413 return t1._ticks != t2._ticks;
416 public static bool operator < (TimeSpan t1, TimeSpan t2)
418 return t1._ticks < t2._ticks;
421 public static bool operator <= (TimeSpan t1, TimeSpan t2)
423 return t1._ticks <= t2._ticks;
426 public static TimeSpan operator - (TimeSpan t1, TimeSpan t2)
428 return t1.Subtract (t2);
431 public static TimeSpan operator - (TimeSpan t)
436 public static TimeSpan operator + (TimeSpan t)
441 // Class Parser implements parser for TimeSpan.Parse
445 private int _cur = 0;
447 private bool formatError;
449 public Parser (string src)
452 _length = _src.Length;
457 return _cur >= _length;
461 // All "Parse" functions throw a FormatException on syntax error.
462 // Their return value is semantic value of the item parsed.
464 // Range checking is spread over three different places:
465 // 1) When parsing "int" values, an exception is thrown immediately
466 // when the value parsed exceeds the maximum value for an int.
467 // 2) An explicit check is built in that checks for hours > 23 and
468 // for minutes and seconds > 59.
469 // 3) Throwing an exceptions for a final TimeSpan value > MaxValue
470 // or < MinValue is left to the TimeSpan constructor called.
472 // Parse zero or more whitespace chars.
473 private void ParseWhiteSpace ()
475 while (!AtEnd && Char.IsWhiteSpace (_src, _cur)) {
480 // Parse optional sign character.
481 private bool ParseSign ()
485 if (!AtEnd && _src[_cur] == '-') {
493 // Parse simple int value
494 private int ParseInt (bool optional)
496 if (optional && AtEnd)
502 while (!AtEnd && Char.IsDigit (_src, _cur)) {
504 res = res * 10 + _src[_cur] - '0';
516 // Parse optional dot
517 private bool ParseOptDot ()
522 if (_src[_cur] == '.') {
529 // Parse optional (LAMESPEC) colon
530 private void ParseOptColon ()
533 if (_src[_cur] == ':')
540 // Parse [1..7] digits, representing fractional seconds (ticks)
541 private long ParseTicks ()
545 bool digitseen = false;
547 while (mag > 0 && !AtEnd && Char.IsDigit (_src, _cur)) {
548 res = res + (_src[_cur] - '0') * mag;
560 public TimeSpan Execute ()
570 // Parse [ws][-][dd.]hh:mm:ss[.ff][ws]
571 // ... but not entirely true as an lonely
572 // integer will be parsed as a number of days
575 days = ParseInt (false);
576 if (ParseOptDot ()) {
577 hours = ParseInt (true);
584 minutes = ParseInt (true);
586 seconds = ParseInt (true);
587 if ( ParseOptDot () ) {
588 ticks = ParseTicks ();
598 // Overflow has presceance over FormatException
599 if (hours > 23 || minutes > 59 || seconds > 59) {
600 throw new OverflowException (
601 Locale.GetText ("Invalid time data."));
603 else if (formatError) {
604 throw new FormatException (
605 Locale.GetText ("Invalid format for TimeSpan.Parse."));
608 long t = TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0);
609 t = checked ((sign) ? (-t - ticks) : (t + ticks));
610 return new TimeSpan (t);