CSharp - Date Time TimeSpan Calculation

Introduction

TimeSpan overloads the < and > operators, as well as the + and - operators.

The following expression evaluates to a TimeSpan of 2.5 hours:

TimeSpan.FromHours(2) + TimeSpan.FromMinutes(30);

The next expression evaluates to one second short of 10 days:

TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1);   // 9.23:59:59

The following code illustrates the integer properties Days, Hours, Minutes, Seconds, and Milliseconds:

Demo

using System;
class MainClass/* ww  w. j  a v  a 2s  .co  m*/
{
    public static void Main(string[] args)
    {
        TimeSpan nearlyTenDays = TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1);

        Console.WriteLine(nearlyTenDays.Days);
        Console.WriteLine(nearlyTenDays.Hours);
        Console.WriteLine(nearlyTenDays.Minutes);
        Console.WriteLine(nearlyTenDays.Seconds);
        Console.WriteLine(nearlyTenDays.Milliseconds);

        //TotalXXX  properties  return  values  of  type  double  describing  the entire time span:

        nearlyTenDays = TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1);

        Console.WriteLine(nearlyTenDays.TotalDays);          // 9.99998842592593
        Console.WriteLine(nearlyTenDays.TotalHours);         // 239.999722222222
        Console.WriteLine(nearlyTenDays.TotalMinutes);       // 14399.9833333333
        Console.WriteLine(nearlyTenDays.TotalSeconds);       // 863999
        Console.WriteLine(nearlyTenDays.TotalMilliseconds);  // 863999000

    }
}

Result

The default value for a TimeSpan is TimeSpan.Zero.

TimeSpan can also be used to represent the time of the day (the elapsed time since midnight).

To obtain the current time of day, call DateTime.Now.TimeOfDay.