C# `TimeSpan.FromDays()`: Creating Timespans Representing Specific Days

Learn how to create `TimeSpan` objects representing a specific number of days in C# using the `TimeSpan.FromDays()` method. This tutorial explains its usage, demonstrates creating `TimeSpan` objects from fractional days, and shows how to access `TimeSpan` components using its properties.



Using C#'s `TimeSpan.FromDays()` Method

The C# `TimeSpan.FromDays()` method creates a `TimeSpan` object representing a specified number of days. `TimeSpan` objects are used to represent time intervals.

Understanding `TimeSpan`

The `TimeSpan` structure in C# is used to represent a time interval. It can store time differences ranging from very short durations (milliseconds) to very long ones (many days). You can obtain a `TimeSpan` by subtracting two `DateTime` objects.

`TimeSpan.FromDays()` Syntax


public static TimeSpan FromDays(double value);

The method takes a `double` value representing the number of days (including fractional days) and returns a new `TimeSpan` object.

Parameters and Return Value

  • value (double): The number of days. Can be positive, negative, or zero. Fractional values represent portions of a day.
  • Return Value: A `TimeSpan` object representing the specified number of days.

Exceptions

  • OverflowException: Thrown if the `value` is outside the range that can be represented by a `TimeSpan`.
  • ArgumentException: (Not directly related to `FromDays()` itself but relevant for TimeSpan in general) Usually thrown when working with invalid TimeSpan values.

`TimeSpan` Properties

The `TimeSpan` structure provides properties to access its components:

  • Days, Hours, Minutes, Seconds, Milliseconds, Ticks: Individual components of the time span.
  • TotalDays, TotalHours, etc.: Total time span in the specified unit.

Example 1: Creating a TimeSpan from Days


TimeSpan ts = TimeSpan.FromDays(52.8799);
Console.WriteLine(ts); // Output will show days, hours, minutes, seconds, milliseconds

Example 2: Handling OverflowException


try {
    TimeSpan ts = TimeSpan.FromDays(double.PositiveInfinity); 
} catch (OverflowException ex) {
    Console.WriteLine($"Error: {ex.Message}");
}