TimeSpan Structure (System)

Switch View :
ScriptFree
.NET Framework Class Library
TimeSpan Structure

Represents a time interval.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Structure TimeSpan _
	Implements IComparable, IComparable(Of TimeSpan),  _
	IEquatable(Of TimeSpan), IFormattable
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, 
	IEquatable<TimeSpan>, IFormattable
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public value class TimeSpan : IComparable, 
	IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
F#
[<Sealed>]
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type TimeSpan =  
    struct
        interface IComparable
        interface IComparable<TimeSpan>
        interface IEquatable<TimeSpan>
        interface IFormattable
    end

The TimeSpan type exposes the following members.

Constructors

  Name Description
Public method Supported by the XNA Framework Supported by Portable Class Library TimeSpan(Int64) Initializes a new TimeSpan to the specified number of ticks.
Public method Supported by the XNA Framework Supported by Portable Class Library TimeSpan(Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of hours, minutes, and seconds.
Public method Supported by the XNA Framework Supported by Portable Class Library TimeSpan(Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, and seconds.
Public method Supported by the XNA Framework Supported by Portable Class Library TimeSpan(Int32, Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.
Top
Properties

  Name Description
Public property Supported by the XNA Framework Supported by Portable Class Library Days Gets the days component of the time interval represented by the current TimeSpan structure.
Public property Supported by the XNA Framework Supported by Portable Class Library Hours Gets the hours component of the time interval represented by the current TimeSpan structure.
Public property Supported by the XNA Framework Supported by Portable Class Library Milliseconds Gets the milliseconds component of the time interval represented by the current TimeSpan structure.
Public property Supported by the XNA Framework Supported by Portable Class Library Minutes Gets the minutes component of the time interval represented by the current TimeSpan structure.
Public property Supported by the XNA Framework Supported by Portable Class Library Seconds Gets the seconds component of the time interval represented by the current TimeSpan structure.
Public property Supported by the XNA Framework Supported by Portable Class Library Ticks Gets the number of ticks that represent the value of the current TimeSpan structure.
Public property Supported by the XNA Framework Supported by Portable Class Library TotalDays Gets the value of the current TimeSpan structure expressed in whole and fractional days.
Public property Supported by the XNA Framework Supported by Portable Class Library TotalHours Gets the value of the current TimeSpan structure expressed in whole and fractional hours.
Public property Supported by the XNA Framework Supported by Portable Class Library TotalMilliseconds Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
Public property Supported by the XNA Framework Supported by Portable Class Library TotalMinutes Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
Public property Supported by the XNA Framework Supported by Portable Class Library TotalSeconds Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.
Top
Methods

  Name Description
Public method Supported by the XNA Framework Supported by Portable Class Library Add Returns a new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Compare Compares two TimeSpan values and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value.
Public method Supported by the XNA Framework CompareTo(Object) Compares this instance to a specified object and returns an integer that indicates whether this instance is shorter than, equal to, or longer than the specified object.
Public method Supported by the XNA Framework Supported by Portable Class Library CompareTo(TimeSpan) Compares this instance to a specified TimeSpan object and returns an integer that indicates whether this instance is shorter than, equal to, or longer than the TimeSpan object.
Public method Supported by the XNA Framework Supported by Portable Class Library Duration Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(Object) Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).)
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(TimeSpan) Returns a value indicating whether this instance is equal to a specified TimeSpan object.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Equals(TimeSpan, TimeSpan) Returns a value that indicates whether two specified instances of TimeSpan are equal.
Protected method Supported by the XNA Framework Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromDays Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromHours Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromMilliseconds Returns a TimeSpan that represents a specified number of milliseconds.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromMinutes Returns a TimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromSeconds Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library FromTicks Returns a TimeSpan that represents a specified time, where the specification is in units of ticks.
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCode Returns a hash code for this instance. (Overrides ValueType.GetHashCode().)
Public method Supported by the XNA Framework Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by the XNA Framework Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Negate Returns a new TimeSpan object whose value is the negated value of this instance.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Parse(String) Converts the string representation of a time interval to its TimeSpan equivalent.
Public method Static member Parse(String, IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.
Public method Static member ParseExact(String, String, IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
Public method Static member ParseExact(String, String[], IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified array of format strings and culture-specific format information. The format of the string representation must match one of the specified formats exactly.
Public method Static member ParseExact(String, String, IFormatProvider, TimeSpanStyles) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format, culture-specific format information, and styles. The format of the string representation must match the specified format exactly.
Public method Static member ParseExact(String, String[], IFormatProvider, TimeSpanStyles) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified formats, culture-specific format information, and styles. The format of the string representation must match one of the specified formats exactly.
Public method Supported by the XNA Framework Supported by Portable Class Library Subtract Returns a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString() Converts the value of the current TimeSpan object to its equivalent string representation. (Overrides ValueType.ToString().)
Public method ToString(String) Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format.
Public method ToString(String, IFormatProvider) Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format and culture-specific formatting information.
Public method Static member Supported by Portable Class Library TryParse(String, TimeSpan) Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.
Public method Static member TryParse(String, IFormatProvider, TimeSpan) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific formatting information, and returns a value that indicates whether the conversion succeeded.
Public method Static member TryParseExact(String, String, IFormatProvider, TimeSpan) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format and culture-specific format information, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match the specified format exactly.
Public method Static member TryParseExact(String, String[], IFormatProvider, TimeSpan) Converts the specified string representation of a time interval to its TimeSpan equivalent by using the specified formats and culture-specific format information, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match one of the specified formats exactly.
Public method Static member TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified format, culture-specific format information, and styles, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match the specified format exactly.
Public method Static member TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan) Converts the specified string representation of a time interval to its TimeSpan equivalent by using the specified formats, culture-specific format information, and styles, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match one of the specified formats exactly.
Top
Operators

  Name Description
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library Addition Adds two specified TimeSpan instances.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library Equality Indicates whether two TimeSpan instances are equal.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library GreaterThan Indicates whether a specified TimeSpan is greater than another specified TimeSpan.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library GreaterThanOrEqual Indicates whether a specified TimeSpan is greater than or equal to another specified TimeSpan.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library Inequality Indicates whether two TimeSpan instances are not equal.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library LessThan Indicates whether a specified TimeSpan is less than another specified TimeSpan.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library LessThanOrEqual Indicates whether a specified TimeSpan is less than or equal to another specified TimeSpan.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library Subtraction Subtracts a specified TimeSpan from another specified TimeSpan.
Public operator Static member Supported by the XNA Framework Supported by Portable Class Library UnaryNegation Returns a TimeSpan whose value is the negated value of the specified instance.
Public operator Static member Supported by Portable Class Library UnaryPlus Returns the specified instance of TimeSpan.
Top
Fields

  Name Description
Public field Static member Supported by the XNA Framework Supported by Portable Class Library MaxValue Represents the maximum TimeSpan value. This field is read-only.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library MinValue Represents the minimum TimeSpan value. This field is read-only.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library TicksPerDay Represents the number of ticks in 1 day. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library TicksPerHour Represents the number of ticks in 1 hour. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library TicksPerMillisecond Represents the number of ticks in 1 millisecond. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library TicksPerMinute Represents the number of ticks in 1 minute. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library TicksPerSecond Represents the number of ticks in 1 second.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library Zero Represents the zero TimeSpan value. This field is read-only.
Top
Remarks

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead. (For more information about using the TimeSpan structure to reflect the time of day, see Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo.)

The largest unit of time that the TimeSpan structure uses to measure duration is a day. Time intervals are measured in days for consistency, because the number of days in larger units of time, such as months and years, varies.

The value of a TimeSpan object is the number of ticks that equal the represented time interval. A tick is equal to 100 nanoseconds, or one ten-millionth of a second. The value of a TimeSpan object can range from TimeSpan.MinValue to TimeSpan.MaxValue.

Instantiating a TimeSpan Value

You can instantiate a TimeSpan value in a number of ways:

  • By calling its implicit default constructor. This creates an object whose value is TimeSpan.Zero, as the following example shows.

    Visual Basic
    
    Dim interval As New TimeSpan()
    Console.WriteLine(interval.Equals(TimeSpan.Zero))     ' Displays "True".
    
    
    
    C#
    
    TimeSpan interval = new TimeSpan();
    Console.WriteLine(interval.Equals(TimeSpan.Zero));    // Displays "True".
    
    
    
  • By calling one of its explicit constructors. The following example initializes a TimeSpan value to a specified number of hours, minutes, and seconds.

    Visual Basic
    
    Dim interval As New TimeSpan(2, 14, 18)
    Console.WriteLine(interval.ToString())                ' Displays "02:14:18".
    
    
    
    C#
    
    TimeSpan interval = new TimeSpan(2, 14, 18);
    Console.WriteLine(interval.ToString());              // Displays "02:14:18".
    
    
    
  • By calling a method or performing an operation that returns a TimeSpan value. For example, you can instantiate a TimeSpan value that represents the interval between two date and time values, as the following example shows.

    Visual Basic
    
    Dim departure As DateTime = #06/12/2010 6:32PM#
    Dim arrival As DateTime = #06/13/2010 10:47PM#
    Dim travelTime As TimeSpan = arrival - departure  
    Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime)      
    ' The example displays the following output:
    '       6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
    
    
    
    C#
    
    DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
    DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
    TimeSpan travelTime = arrival - departure;  
    Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime);      
    // The example displays the following output:
    //       6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
    
    
    

    TimeSpan values are returned by arithmetic operators and methods of the DateTime, DateTimeOffset, and TimeSpan structures.

  • By parsing the string representation of a TimeSpan value. You can use the Parse and TryParse methods to convert strings that contain time intervals to TimeSpan values. The following example uses the Parse method to convert an array of strings to TimeSpan values.

    Visual Basic
    
    Dim values() As String = { "12", "31.", "5.8:32:16", "12:12:15.95", ".12"}
    For Each value As String In values
       Try
          Dim ts As TimeSpan = TimeSpan.Parse(value)
          Console.WriteLine("'{0}' --> {1}", value, ts)
       Catch e As FormatException
          Console.WriteLine("Unable to parse '{0}'", value)
       Catch e As OverflowException
          Console.WriteLine("'{0}' is outside the range of a TimeSpan.", value)
       End Try   
    Next
    ' The example displays the following output:
    '       '12' --> 12.00:00:00
    '       Unable to parse '31.'
    '       '5.8:32:16' --> 5.08:32:16
    '       '12:12:15.95' --> 12:12:15.9500000
    '       Unable to parse '.12'  
    
    
    
    C#
    
    string[] values = { "12", "31.", "5.8:32:16", "12:12:15.95", ".12"};
    foreach (string value in values)
    {
       try {
          TimeSpan ts = TimeSpan.Parse(value);
          Console.WriteLine("'{0}' --> {1}", value, ts);
       }
       catch (FormatException) {
          Console.WriteLine("Unable to parse '{0}'", value);
       }
       catch (OverflowException) {
          Console.WriteLine("'{0}' is outside the range of a TimeSpan.", value);
       }   
    }
    // The example displays the following output:
    //       '12' --> 12.00:00:00
    //       Unable to parse '31.'
    //       '5.8:32:16' --> 5.08:32:16
    //       '12:12:15.95' --> 12:12:15.9500000
    //       Unable to parse '.12'  
    
    
    

    In addition, you can define the precise format of the input string to be parsed and converted to a TimeSpan value by calling the ParseExact or TryParseExact method.

Performing Operations on TimeSpan Values

You can add and subtract time durations either by using the Addition and Subtraction operators, or by calling the Add and Subtract methods. You can also compare two time durations by calling the Compare, CompareTo, and Equals methods. The TimeSpan class also includes the Duration and Negate methods, which convert time intervals to positive and negative values,

The range of TimeSpan values is MinValue to MaxValue.

Formatting a TimeSpan Value

A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. That is, a time interval consists of a positive or negative number of days without a time of day, or a number of days with a time of day, or only a time of day.

Beginning with the .NET Framework version 4, the TimeSpan structure supports culture-sensitive formatting through the overloads of its ToString method, which converts a TimeSpan value to its string representation. The default TimeSpan.ToString() method returns a time interval by using an invariant format that is identical to its return value in previous versions of the .NET Framework. The TimeSpan.ToString(String) overload lets you specify a format string that defines the string representation of the time interval. The TimeSpan.ToString(String, IFormatProvider) overload lets you specify a format string and the culture whose formatting conventions are used to create the string representation of the time interval. TimeSpan supports both standard and custom format strings. (For more information, see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.) However, only standard format strings are culture-sensitive.

Restoring Legacy TimeSpan Formatting

In some cases, code that successfully formats TimeSpan values in .NET Framework 3.5 and earlier versions fails in .NET Framework 4. This is most common in code that calls a composite formatting method to format a TimeSpan value with a format string. The following example successfully formats a TimeSpan value in .NET Framework 3.5 and earlier versions, but throws an exception in .NET Framework 4 and later versions. Note that it attempts to format a TimeSpan value by using an unsupported format specifier, which is ignored in .NET Framework 3.5 and earlier versions.

Visual Basic

Dim interval As New TimeSpan(12, 30, 45)
Dim output As String
Try
   output = String.Format("{0:r}", interval)
Catch e As FormatException
   output = "Invalid Format"
End Try
Console.WriteLine(output)
' Output from .NET Framework 3.5 and earlier versions:
'       12:30:45
' Output from .NET Framework 4:
'       Invalid Format


C#

TimeSpan interval = new TimeSpan(12, 30, 45);
string output;
try {
   output = String.Format("{0:r}", interval);
}
catch (FormatException) {
   output = "Invalid Format";
}
Console.WriteLine(output);
// Output from .NET Framework 3.5 and earlier versions:
//       12:30:45
// Output from .NET Framework 4:
//       Invalid Format


If you cannot modify the code, you can restore the legacy formatting of TimeSpan values in one of the following ways:

  • By creating a configuration file that contains the <TimeSpan_LegacyFormatMode> element. Setting this element's enabled attribute to true restores legacy TimeSpan formatting on a per-application basis.

  • By setting the "NetFx40_TimeSpanLegacyFormatMode" compatibility switch when you create an application domain. This enables legacy TimeSpan formatting on a per-application-domain basis. The following example creates an application domain that uses legacy TimeSpan formatting.

    Visual Basic
    
    Module Example
       Public Sub Main()
          Dim appSetup As New AppDomainSetup()
          appSetup.SetCompatibilitySwitches( { "NetFx40_TimeSpanLegacyFormatMode" } )
          Dim legacyDomain As AppDomain = AppDomain.CreateDomain("legacyDomain", 
                                                                 Nothing, appSetup)
          legacyDomain.ExecuteAssembly("ShowTimeSpan.exe")
       End Sub
    End Module
    
    
    
    C#
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          AppDomainSetup appSetup = new AppDomainSetup();
          appSetup.SetCompatibilitySwitches( new string[] { "NetFx40_TimeSpanLegacyFormatMode" } );
          AppDomain legacyDomain = AppDomain.CreateDomain("legacyDomain", 
                                                          null, appSetup);
          legacyDomain.ExecuteAssembly("ShowTimeSpan.exe");
       }
    }
    
    
    

    When the following code executes in the new application domain, it reverts to legacy TimeSpan formatting behavior.

    Visual Basic
    
    Module Example
       Public Sub Main()
          Dim interval As TimeSpan = Date.Now - Date.Now.Date
          Dim msg As String = String.Format("Elapsed Time Today: {0:d} hours.",
                                             interval)
          Console.WriteLine(msg)
       End Sub
    End Module
    ' The example displays output like the following:
    '       Elapsed Time Today: 01:40:52.2524662 hours.
    
    
    
    C#
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          TimeSpan interval = DateTime.Now - DateTime.Now.Date;
          string msg = String.Format("Elapsed Time Today: {0:d} hours.",
                                     interval);
          Console.WriteLine(msg);
       }
    }
    // The example displays the following output:
    //       Elapsed Time Today: 01:40:52.2524662 hours.
    
    
    
Examples

The following example instantiates a TimeSpan object that represents the difference between two dates. It then displays the TimeSpan object's properties.

Visual Basic

' Define two dates.
Dim date1 As Date = #1/1/2010 8:00:15AM#
Dim date2 As Date = #8/18/2010 1:30:30PM#
' Calculate the interval between the two dates.
Dim interval As TimeSpan = date2 - date1
Console.WriteLine("{0} - {1} = {2}", date2, date1, interval.ToString())
' Display individual properties of the resulting TimeSpan object.
Console.WriteLine("   {0,-35} {1,20}", "Value of Days Component:", interval.Days)
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Days:", interval.TotalDays)
Console.WriteLine("   {0,-35} {1,20}", "Value of Hours Component:", interval.Hours)
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Hours:", interval.TotalHours)
Console.WriteLine("   {0,-35} {1,20}", "Value of Minutes Component:", interval.Minutes)
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Minutes:", interval.TotalMinutes)
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Seconds Component:", interval.Seconds)
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Seconds:", interval.TotalSeconds)
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Milliseconds Component:", interval.Milliseconds)
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Milliseconds:", interval.TotalMilliseconds)
Console.WriteLine("   {0,-35} {1,20:N0}", "Ticks:", interval.Ticks)
' The example displays the following output:
'       8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
'          Value of Days Component:                             229
'          Total Number of Days:                   229.229340277778
'          Value of Hours Component:                              5
'          Total Number of Hours:                  5501.50416666667
'          Value of Minutes Component:                           30
'          Total Number of Minutes:                       330090.25
'          Value of Seconds Component:                           15
'          Total Number of Seconds:                      19,805,415
'          Value of Milliseconds Component:                       0
'          Total Number of Milliseconds:             19,805,415,000
'          Ticks:                               198,054,150,000,000


C#

// Define two dates.
DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30);
// Calculate the interval between the two dates.
TimeSpan interval = date2 - date1;
Console.WriteLine("{0} - {1} = {2}", date2, date1, interval.ToString());
// Display individual properties of the resulting TimeSpan object.
Console.WriteLine("   {0,-35} {1,20}", "Value of Days Component:", interval.Days);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Days:", interval.TotalDays);
Console.WriteLine("   {0,-35} {1,20}", "Value of Hours Component:", interval.Hours);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Hours:", interval.TotalHours);
Console.WriteLine("   {0,-35} {1,20}", "Value of Minutes Component:", interval.Minutes);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Minutes:", interval.TotalMinutes);
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Seconds Component:", interval.Seconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Seconds:", interval.TotalSeconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Milliseconds Component:", interval.Milliseconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Milliseconds:", interval.TotalMilliseconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Ticks:", interval.Ticks);
// the example displays the following output:
//       8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
//          Value of Days Component:                             229
//          Total Number of Days:                   229.229340277778
//          Value of Hours Component:                              5
//          Total Number of Hours:                  5501.50416666667
//          Value of Minutes Component:                           30
//          Total Number of Minutes:                       330090.25
//          Value of Seconds Component:                           15
//          Total Number of Seconds:                      19,805,415
//          Value of Milliseconds Component:                       0
//          Total Number of Milliseconds:             19,805,415,000
//          Ticks:                               198,054,150,000,000


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Community Content

Niels Grove-Rasmussen
Usage in PowerShell

A DateTime object can be created in various ways, e.g. with the cmdlet New-Object

$tstart = New-Object System.DateTime(2010,6,12,18,32,0)

Also a DateTime object can be created with the cmdlet Get-Date

$tend = Get-Date "2010-06-13 22:47"

The difference is calculated with the subtraction operator ("-")

$tend - $tstart

and the output indicates a TimeSpan object

Days              
: 
1
Hours             : 4
Minutes           : 15
Seconds           : 0
Milliseconds      : 0
Ticks             : 1017000000000
TotalDays         : 1,17708333333333
TotalHours        : 28,25
TotalMinutes      : 1695
TotalSeconds      : 101700
TotalMilliseconds : 101700000

The type of the output is a TimeSpan object, which can be verified with this statement

$tend - $tstart | Get-Member

The output is

   TypeName: 
System.TimeSpanName              
MemberType 
Definition
----              ---------- ----------
Add               Method     System.TimeSpan Add(System.TimeSpan ts)
CompareTo         Method     int CompareTo(System.Object value), int CompareTo(System.TimeSpan value)
Duration          Method     System.TimeSpan Duration()
Equals            Method     bool Equals(System.Object value), bool Equals(System.TimeSpan obj)
GetHashCode       Method     int GetHashCode()
GetType           Method     type GetType()
Negate            Method     System.TimeSpan Negate()
Subtract          Method     System.TimeSpan Subtract(System.TimeSpan ts)
ToString          Method     string ToString()
Days              Property   System.Int32 Days {get;}
Hours             Property   System.Int32 Hours {get;}
Milliseconds      Property   System.Int32 Milliseconds {get;}
Minutes           Property   System.Int32 Minutes {get;}
Seconds           Property   System.Int32 Seconds {get;}
Ticks             Property   System.Int64 Ticks {get;}
TotalDays         Property   System.Double TotalDays {get;}
TotalHours        Property   System.Double TotalHours {get;}
TotalMilliseconds Property   System.Double TotalMilliseconds {get;}
TotalMinutes      Property   System.Double TotalMinutes {get;}
TotalSeconds      Property   System.Double TotalSeconds {get;}

The result can be formatted to a shorter output

($tend - $tstart).ToString()

Thomas Lee
TimeSpan Demo - Recoded in PowerShell
<#
.SYNOPSIS
This script, a re-implementation of an MSDN sample, shows the
Unicode details of a unicode character, using PowerShell.
.DESCRIPTION
This script re-implments a simple MSDN script that takes a Unicode Character
and uses CharUnicodeInfo class to get details of that character, which are then
displayed on the console.
.NOTES
File Name : Show-TimeSpan.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
MSDN sample posted to:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx
.EXAMPLE
Psh> .\Show-TimeSpan.ps1
8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
Value of Days Component: 229
Total Number of Days: 229.229340277778
Value of Hours Component: 5
Total Number of Hours: 5501.50416666667
Value of Minutes Component: 30
Total Number of Minutes: 330090.25
Value of Seconds Component: 15
Total Number of Seconds: 19,805,415
Value of Milliseconds Component: 0
Total Number of Milliseconds: 19,805,415,000
Ticks: 198,054,150,000,000
#>

# Define two dates
$date1 = new-object system.datetime 2010, 1, 1, 8, 0, 15
$date2 = new-object system.datetime 2010, 8, 18, 13, 30, 30

# Create a time Interval
$interval = New-Timespan -start $date1 -end $date2

#Display the interval
"{0} - {1} = {2}" -f $date2, $date1, $interval.ToString()

# Display individual properties of the resulting TimeSpan object.
" {0,-35} {1,20}" -f "Value of Days Component:", $interval.Days
" {0,-35} {1,20}" -f "Total Number of Days:", $interval.TotalDays
" {0,-35} {1,20}" -f "Value of Hours Component:", $interval.Hours
" {0,-35} {1,20}" -f "Total Number of Hours:", $interval.TotalHours
" {0,-35} {1,20}" -f "Value of Minutes Component:", $interval.Minutes
" {0,-35} {1,20}" -f "Total Number of Minutes:", $interval.TotalMinutes
" {0,-35} {1,20:N0}" -f "Value of Seconds Component:", $interval.Seconds
" {0,-35} {1,20:N0}" -f "Total Number of Seconds:", $interval.TotalSeconds
" {0,-35} {1,20:N0}" -f "Value of Milliseconds Component:", $interval.Milliseconds
" {0,-35} {1,20:N0}" -f "Total Number of Milliseconds:", $interval.TotalMilliseconds
" {0,-35} {1,20:N0}" -f "Ticks:", $interval.Ticks

Burton-Radons
Clarification regarding time range
The remarks say that "The largest unit of time that the TimeSpan structure uses to measure duration is a day." What this means is that the largest unit it will return is the day, NOT that it can only measure time spans of a single day. As the remarks do say, the measurable range is TimeSpan.MinValue to TimeSpan.MaxValue, which is of this writing with Framework 4 around -30k to 30k years respectively.