Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timespan(0,0,secs) or Timespan.FromSeconds(secs)

Is there a difference in the returned values between Timespan(0,0,secs) and Timespan.FromSeconds(secs)?

It seems to me the difference is that FromSeconds accepts a double.

like image 413
Yariv Avatar asked Dec 09 '22 09:12

Yariv


2 Answers

Ultimately no, under the hood, TimeSpan deals with ticks.

Personally I would prefer to use TimeSpan.FromSeconds as it is completely clear what the intent is.

like image 182
Trevor Pilley Avatar answered Dec 11 '22 08:12

Trevor Pilley


The parameter being a double in the second case is an important difference indeed: in some cases it can lead to an OverflowException. Quoting the documentation below.

TimeSpan Constructor (Int32, Int32, Int32):

The specified hours, minutes, and seconds are converted to ticks, and that value initializes this instance.

TimeSpan.FromSeconds Method:

The value parameter is converted to milliseconds, which is converted to ticks, and that number of ticks is used to intialize the new TimeSpan. Therefore, value will only be considered accurate to the nearest millisecond. Note that, because of the loss of precision of the Double data type, this can generate an OverflowException for values that are near but still in the range of either MinValue or MaxValue, This is the cause of an OverflowException, for example, in the following attempt to instantiate a TimeSpan object.

// The following throws an OverflowException at runtime
TimeSpan maxSpan = TimeSpan.FromSeconds(TimeSpan.MaxValue.TotalSeconds);
like image 41
user247702 Avatar answered Dec 11 '22 09:12

user247702