CSharp - Date Time TimeSpan Type

Introduction

TimeSpan represents an interval of time.

You can also use TimeSpan to represent "clock" time without the date for today's time since midnight, assuming no daylight saving transition.

A TimeSpan has a resolution of 100 ns, has a maximum value of about 10 million days, and can be positive or negative.

There are three ways to construct a TimeSpan:

  • Through one of the constructors
  • By calling one of the static From... methods
  • By subtracting one DateTime from another

Here are the constructors:

public TimeSpan (int hours, int minutes, int seconds);
public TimeSpan (int days, int hours, int minutes, int seconds);
public TimeSpan (int days, int hours, int minutes, int seconds,
                 int milliseconds);
public TimeSpan (long ticks);   // Each tick = 100ns

static FromXXX methods can accept an interval in just a single unit, such as minutes, hours, and so on:

public static TimeSpan FromDays (double value);
public static TimeSpan FromHours (double value);
public static TimeSpan FromMinutes (double value);
public static TimeSpan FromSeconds (double value);
public static TimeSpan FromMilliseconds (double value);

For example:

Demo

using System;
class MainClass//from w w  w .j  a  va 2s . co  m
{
   public static void Main(string[] args)
   {
     Console.WriteLine (new TimeSpan (2, 30, 0));     // 02:30:00
     Console.WriteLine (TimeSpan.FromHours (2.5));    // 02:30:00
     Console.WriteLine (TimeSpan.FromHours (-2.5));   // -02:30:00
   }
}

Result