Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System Namespace
TimeSpan Structure
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
TimeSpan Structure

Updated: August 2009

Represents a time interval.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Structure TimeSpan _
    Implements IComparable, IComparable(Of TimeSpan),  _
    IEquatable(Of TimeSpan)
Visual Basic (Usage)
Dim instance As TimeSpan
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, 
    IEquatable<TimeSpan>
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public value class TimeSpan : IComparable, 
    IComparable<TimeSpan>, IEquatable<TimeSpan>
JScript
JScript supports the use of structures, but not the declaration of new ones.

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.

The largest unit of time used 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, and 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'  
    

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. For example, the text representation of a TimeSpan object initialized to 1.0e+13 ticks is "11.13:46:40", which means 11 days, 13 hours, 46 minutes, and 40 seconds.

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
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

August 2009

Expanded the Remarks section and replaced the example.

Customer feedback.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Display-TimeSpan.ps1      Thomas Lee   |   Edit   |   Show History
# Display-Timespan.ps1
# Creates timespan objects and displays properties for each
# Thomas Lee - tfl@psp.co.uk
  

# Constants

$HeaderFmt ="`n{0, -45}"

$DataFmt ="{0,-12}{1,8} {2,-18}{3,21}"

# Helper function

function ShowTimeSpanProperties {

param ([System.TimeSpan] $Interval= 1)

# Display the properties of the TimeSpan parameter.

"Interval = {0,21}" -f $interval

"$DataFmt" -f "Days", $interval.Days, "TotalDays", $interval.TotalDays

"$DataFmt" -f "Hours", $interval.Hours, "TotalHours", $interval.TotalHours

"$dataFmt" -f "Minutes", $interval.Minutes, "TotalMinutes", $interval.TotalMinutes

"$DataFmt" -f "Seconds", $interval.Seconds, "TotalSeconds", $interval.TotalSeconds

"$DataFmt" -f "Milliseconds", $interval.Milliseconds, "TotalMilliseconds", $interval.TotalMilliseconds

"$DataFmt" -f $null, $null, "Ticks", $interval.Ticks

}

# Start of script

# Create and display a comment

"

This example of the TimeSpan class properties

generates the following output. It creates

several TimeSpan objects and displays the values

of the TimeSpan properties for each

"

# Create and display a TimeSpan value of 1 tick.

$ts = [system.TimeSpan] 1

"$HeaderFmt" -f "TimeSpan( 1 )"

ShowTimeSpanProperties($ts)

# Create a TimeSpan value with a large number of ticks.

$ts = [System.TimeSpan] 111222333444555

"$HeaderFmt" -f "TimeSpan( 111222333444555 )"

ShowTimeSpanProperties($ts)



# This TimeSpan has all fields specified.

$ts=New-ObjectSystem.TimeSpan 10, 20, 30, 40, 50

"$HeaderFmt" -f "TimeSpan( 10, 20, 30, 40, 50 )"

ShowTimeSpanProperties($ts)

# This TimeSpan has all fields overflowing.

$ts=New-ObjectSystem.Timespan 1111, 2222, 3333, 4444, 5555

"$HeaderFmt" -f "TimeSpan( 1111, 2222, 3333, 4444, 5555 )"

ShowTimeSpanProperties($ts)

# This TimeSpan is based on a number of days.

$ts = [system.TimeSpan] ([system.TimeSpan]::FromDays(20.8474560))

"$headerFmt" -f "FromDays( 20.84745602 )"

ShowTimeSpanProperties ($ts)


This script produces the following output:

  
PS C:\foo> .\displayTimeSpan.ps1
This example of the TimeSpan class properties
generates the following output. It creates
several TimeSpan objects and displays the values
of the TimeSpan properties for each
  
TimeSpan( 1 )
Interval = 00:00:00.0000001
Days 0 TotalDays 1.15740740740741E-12
Hours 0 TotalHours 2.77777777777778E-11
Minutes 0 TotalMinutes 1.66666666666667E-09
Seconds 0 TotalSeconds 1E-07
Milliseconds 0 TotalMilliseconds 0.0001
Ticks 1
  
TimeSpan( 111222333444555 )
Interval = 128.17:30:33.3444555
Days 128 TotalDays 128.729552597865
Hours 17 TotalHours 3089.50926234875
Minutes 30 TotalMinutes 185370.555740925
Seconds 33 TotalSeconds 11122233.3444555
Milliseconds 344 TotalMilliseconds 11122233344.4555
Ticks 111222333444555
  
TimeSpan( 10, 20, 30, 40, 50 )
Interval = 10.20:30:40.0500000
Days 10 TotalDays 10.8546302083333
Hours 20 TotalHours 260.511125
Minutes 30 TotalMinutes 15630.6675
Seconds 40 TotalSeconds 937840.05
Milliseconds 50 TotalMilliseconds 937840050
Ticks 9378400500000
  
TimeSpan( 1111, 2222, 3333, 4444, 5555 )
Interval = 1205.22:47:09.5550000
Days 1205 TotalDays 1205.94941614583
Hours 22 TotalHours 28942.7859875
Minutes 47 TotalMinutes 1736567.15925
Seconds 9 TotalSeconds 104194029.555
Milliseconds 555 TotalMilliseconds 104194029555
Ticks 1041940295550000
  
FromDays( 20.84745602 )
Interval = 20.20:20:20.1980000
Days 20 TotalDays 20.8474559953704
Hours 20 TotalHours 500.338943888889
Minutes 20 TotalMinutes 30020.3366333333
Seconds 20 TotalSeconds 1801220.198
Milliseconds 198 TotalMilliseconds 1801220198
Ticks 18012201980000

Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker