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 :
40 IComparable, IComparable<TimeSpan>
45 public static readonly TimeSpan MaxValue = new TimeSpan (long.MaxValue);
46 public static readonly TimeSpan MinValue = new TimeSpan (long.MinValue);
47 public static readonly TimeSpan Zero = new TimeSpan (0L);
49 public const long TicksPerDay = 864000000000L;
50 public const long TicksPerHour = 36000000000L;
51 public const long TicksPerMillisecond = 10000L;
52 public const long TicksPerMinute = 600000000L;
53 public const long TicksPerSecond = 10000000L;
57 public TimeSpan (long value)
62 public TimeSpan (int hours, int minutes, int seconds)
64 _ticks = CalculateTicks (0, hours, minutes, seconds, 0);
67 public TimeSpan (int days, int hours, int minutes, int seconds)
69 _ticks = CalculateTicks (days, hours, minutes, seconds, 0);
72 public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds)
74 _ticks = CalculateTicks (days, hours, minutes, seconds, milliseconds);
77 internal static long CalculateTicks (int days, int hours, int minutes, int seconds, int milliseconds)
79 // there's no overflow checks for hours, minutes, ...
80 // so big hours/minutes values can overflow at some point and change expected values
81 int hrssec = (hours * 3600); // break point at (Int32.MaxValue - 596523)
82 int minsec = (minutes * 60);
83 long t = ((long)(hrssec + minsec + seconds) * 1000L + (long)milliseconds);
86 bool overflow = false;
87 // days is problematic because it can overflow but that overflow can be
88 // "legal" (i.e. temporary) (e.g. if other parameters are negative) or
89 // illegal (e.g. sign change).
91 long td = TicksPerDay * days;
95 // positive days -> total ticks should be lower
96 overflow = (ticks > t);
100 // positive + positive != negative result
105 long td = TicksPerDay * days;
108 // negative + negative != positive result
114 // negative days -> total ticks should be lower
115 overflow = (t > ticks);
120 throw new ArgumentOutOfRangeException (Locale.GetText ("The timespan is too big or too small."));
127 return (int) (_ticks / TicksPerDay);
133 return (int) (_ticks % TicksPerDay / TicksPerHour);
137 public int Milliseconds {
139 return (int) (_ticks % TicksPerSecond / TicksPerMillisecond);
145 return (int) (_ticks % TicksPerHour / TicksPerMinute);
151 return (int) (_ticks % TicksPerMinute / TicksPerSecond);
161 public double TotalDays {
163 return (double) _ticks / TicksPerDay;
167 public double TotalHours {
169 return (double) _ticks / TicksPerHour;
173 public double TotalMilliseconds {
175 return (double) _ticks / TicksPerMillisecond;
179 public double TotalMinutes {
181 return (double) _ticks / TicksPerMinute;
185 public double TotalSeconds {
187 return (double) _ticks / TicksPerSecond;
191 public TimeSpan Add (TimeSpan ts)
195 return new TimeSpan (_ticks + ts.Ticks);
198 catch (OverflowException) {
199 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
203 public static int Compare (TimeSpan t1, TimeSpan t2)
205 if (t1._ticks < t2._ticks)
207 if (t1._ticks > t2._ticks)
212 public int CompareTo (object value)
217 if (!(value is TimeSpan)) {
218 throw new ArgumentException (Locale.GetText ("Argument has to be a TimeSpan."), "value");
221 return Compare (this, (TimeSpan) value);
225 public int CompareTo (TimeSpan value)
227 return Compare (this, value);
230 public bool Equals (TimeSpan value)
232 return value._ticks == _ticks;
236 public TimeSpan Duration ()
240 return new TimeSpan (Math.Abs (_ticks));
243 catch (OverflowException) {
244 throw new OverflowException (Locale.GetText (
245 "This TimeSpan value is MinValue so you cannot get the duration."));
249 public override bool Equals (object value)
251 if (!(value is TimeSpan))
254 return _ticks == ((TimeSpan) value)._ticks;
257 public static bool Equals (TimeSpan t1, TimeSpan t2)
259 return t1._ticks == t2._ticks;
262 public static TimeSpan FromDays (double value)
264 return From (value, TicksPerDay);
267 public static TimeSpan FromHours (double value)
269 return From (value, TicksPerHour);
272 public static TimeSpan FromMinutes (double value)
274 return From (value, TicksPerMinute);
277 public static TimeSpan FromSeconds (double value)
279 return From (value, TicksPerSecond);
282 public static TimeSpan FromMilliseconds (double value)
284 return From (value, TicksPerMillisecond);
287 private static TimeSpan From (double value, long tickMultiplicator)
289 if (Double.IsNaN (value))
290 throw new ArgumentException (Locale.GetText ("Value cannot be NaN."), "value");
291 if (Double.IsNegativeInfinity (value) || Double.IsPositiveInfinity (value) ||
292 (value < MinValue.Ticks) || (value > MaxValue.Ticks))
293 throw new OverflowException (Locale.GetText ("Outside range [MinValue,MaxValue]"));
296 value = (value * (tickMultiplicator / TicksPerMillisecond));
299 long val = (long) Math.Round(value);
300 return new TimeSpan (val * TicksPerMillisecond);
303 catch (OverflowException) {
304 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
308 public static TimeSpan FromTicks (long value)
310 return new TimeSpan (value);
313 public override int GetHashCode ()
315 return _ticks.GetHashCode ();
318 public TimeSpan Negate ()
320 if (_ticks == MinValue._ticks)
321 throw new OverflowException (Locale.GetText (
322 "This TimeSpan value is MinValue and cannot be negated."));
323 return new TimeSpan (-_ticks);
326 public static TimeSpan Parse (string s)
329 throw new ArgumentNullException ("s");
332 Parser p = new Parser (s);
336 public TimeSpan Subtract (TimeSpan ts)
340 return new TimeSpan (_ticks - ts.Ticks);
343 catch (OverflowException) {
344 throw new OverflowException (Locale.GetText ("Resulting timespan is too big."));
348 public override string ToString ()
350 StringBuilder sb = new StringBuilder (14);
355 // We need to take absolute values of all components.
356 // Can't handle negative timespans by negating the TimeSpan
357 // as a whole. This would lead to an overflow for the
358 // degenerate case "TimeSpan.MinValue.ToString()".
360 sb.Append (Math.Abs (Days));
364 sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (Hours), 2, 4));
366 sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (Minutes), 2, 4));
368 sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (Seconds), 2, 4));
370 int fractional = (int) Math.Abs (_ticks % TicksPerSecond);
371 if (fractional != 0) {
373 sb.Append (IntegerFormatter.FormatDecimal (Math.Abs (fractional), 7, 4));
376 return sb.ToString ();
379 public static TimeSpan operator + (TimeSpan t1, TimeSpan t2)
384 public static bool operator == (TimeSpan t1, TimeSpan t2)
386 return t1._ticks == t2._ticks;
389 public static bool operator > (TimeSpan t1, TimeSpan t2)
391 return t1._ticks > t2._ticks;
394 public static bool operator >= (TimeSpan t1, TimeSpan t2)
396 return t1._ticks >= t2._ticks;
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 TimeSpan operator - (TimeSpan t1, TimeSpan t2)
416 return t1.Subtract (t2);
419 public static TimeSpan operator - (TimeSpan t)
424 public static TimeSpan operator + (TimeSpan t)
429 // Class Parser implements parser for TimeSpan.Parse
433 private int _cur = 0;
435 private bool formatError;
437 public Parser (string src)
440 _length = _src.Length;
445 return _cur >= _length;
449 // All "Parse" functions throw a FormatException on syntax error.
450 // Their return value is semantic value of the item parsed.
452 // Range checking is spread over three different places:
453 // 1) When parsing "int" values, an exception is thrown immediately
454 // when the value parsed exceeds the maximum value for an int.
455 // 2) An explicit check is built in that checks for hours > 23 and
456 // for minutes and seconds > 59.
457 // 3) Throwing an exceptions for a final TimeSpan value > MaxValue
458 // or < MinValue is left to the TimeSpan constructor called.
460 // Parse zero or more whitespace chars.
461 private void ParseWhiteSpace ()
463 while (!AtEnd && Char.IsWhiteSpace (_src, _cur)) {
468 // Parse optional sign character.
469 private bool ParseSign ()
473 if (!AtEnd && _src[_cur] == '-') {
481 // Parse simple int value
482 private int ParseInt (bool optional)
484 if (optional && AtEnd)
490 while (!AtEnd && Char.IsDigit (_src, _cur)) {
492 res = res * 10 + _src[_cur] - '0';
504 // Parse optional dot
505 private bool ParseOptDot ()
510 if (_src[_cur] == '.') {
517 // Parse optional (LAMESPEC) colon
518 private void ParseOptColon ()
521 if (_src[_cur] == ':')
528 // Parse [1..7] digits, representing fractional seconds (ticks)
529 private long ParseTicks ()
533 bool digitseen = false;
535 while (mag > 0 && !AtEnd && Char.IsDigit (_src, _cur)) {
536 res = res + (_src[_cur] - '0') * mag;
548 public TimeSpan Execute ()
558 // Parse [ws][-][dd.]hh:mm:ss[.ff][ws]
559 // ... but not entirely true as an lonely
560 // integer will be parsed as a number of days
563 days = ParseInt (false);
564 if (ParseOptDot ()) {
565 hours = ParseInt (true);
572 minutes = ParseInt (true);
574 seconds = ParseInt (true);
575 if ( ParseOptDot () ) {
576 ticks = ParseTicks ();
586 // Overflow has presceance over FormatException
587 if (hours > 23 || minutes > 59 || seconds > 59) {
588 throw new OverflowException (
589 Locale.GetText ("Invalid time data."));
591 else if (formatError) {
592 throw new FormatException (
593 Locale.GetText ("Invalid format for TimeSpan.Parse."));
596 long t = TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0);
597 t = checked ((sign) ? (-t - ticks) : (t + ticks));
598 return new TimeSpan (t);