TimeSpan 结构

定义

表示一个时间间隔。

public value class TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
public value class TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, ISpanFormattable
public value class TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IParsable<TimeSpan>, ISpanFormattable, ISpanParsable<TimeSpan>
public value class TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IParsable<TimeSpan>, ISpanFormattable, ISpanParsable<TimeSpan>, IUtf8SpanFormattable
public value class TimeSpan : IComparable
public value class TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>
public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
public readonly struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
public readonly struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, ISpanFormattable
public readonly struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IParsable<TimeSpan>, ISpanFormattable, ISpanParsable<TimeSpan>
public readonly struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IParsable<TimeSpan>, ISpanFormattable, ISpanParsable<TimeSpan>, IUtf8SpanFormattable
[System.Serializable]
public struct TimeSpan : IComparable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
type TimeSpan = struct
    interface IFormattable
type TimeSpan = struct
    interface ISpanFormattable
    interface IFormattable
type TimeSpan = struct
    interface IFormattable
    interface IParsable<TimeSpan>
    interface ISpanFormattable
    interface ISpanParsable<TimeSpan>
type TimeSpan = struct
    interface IFormattable
    interface IParsable<TimeSpan>
    interface ISpanFormattable
    interface ISpanParsable<TimeSpan>
    interface IUtf8SpanFormattable
[<System.Serializable>]
type TimeSpan = struct
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type TimeSpan = struct
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type TimeSpan = struct
    interface IFormattable
Public Structure TimeSpan
Implements IComparable, IComparable(Of TimeSpan), IEquatable(Of TimeSpan), IFormattable
Public Structure TimeSpan
Implements IComparable, IComparable(Of TimeSpan), IEquatable(Of TimeSpan), ISpanFormattable
Public Structure TimeSpan
Implements IComparable, IComparable(Of TimeSpan), IEquatable(Of TimeSpan), IParsable(Of TimeSpan), ISpanFormattable, ISpanParsable(Of TimeSpan)
Public Structure TimeSpan
Implements IComparable, IComparable(Of TimeSpan), IEquatable(Of TimeSpan), IParsable(Of TimeSpan), ISpanFormattable, ISpanParsable(Of TimeSpan), IUtf8SpanFormattable
Public Structure TimeSpan
Implements IComparable
Public Structure TimeSpan
Implements IComparable, IComparable(Of TimeSpan), IEquatable(Of TimeSpan)
继承
TimeSpan
属性
实现

示例

以下示例实例化一个 对象,该对象表示两个 TimeSpan 日期之间的差异。 然后, TimeSpan 它显示对象的属性。

// 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);

// This 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
// Define two dates.
let date1 = DateTime(2010, 1, 1, 8, 0, 15)
let date2 = DateTime(2010, 8, 18, 13, 30, 30)

// Calculate the interval between the two dates.
let interval = date2 - date1
printfn $"{date2} - {date1} = {interval}"

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

// This 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
' 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
# Define two dates.
$Date2 = Get-Date -Date '2010/8/18' -Hour 13 -Minute 30 -Second 30
$Date1 = Get-Date -Date '2010/1/1'  -Hour 8  -Minute 0  -Second 15

# Calculate the interval between the two dates.
$Interval = $Date2 - $Date1
"{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

<# This sample produces the following output:

18/08/2010 13:30:30 - 01/01/2010 08:00:15 = 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
#>

注解

TimeSpan对象表示时间间隔 (持续时间或经过时间) ,以正数或负数天、小时数、分钟数、秒数和秒小数来度量。 结构 TimeSpan 还可用于表示一天中的时间,但前提是时间与特定日期无关。 否则, DateTime 应改用 或 DateTimeOffset 结构。 (有关使用 TimeSpan 结构反映一天中时间的详细信息,请参阅 在 DateTime、DateTimeOffset、TimeSpan 和 TimeZoneInfo 之间选择)

注意

TimeSpan 表示时间间隔,可以表示为特定的天数、小时数、分钟数、秒数和毫秒。 由于它表示一个不引用特定起点或终点的常规间隔,因此不能用年和月来表示,这两者都有可变的天数。 它不同于 DateTime 值,该值表示不引用特定时区的日期和时间,或 DateTimeOffset 表示特定时间刻的值。

结构用于度量持续时间的最大时间 TimeSpan 单位是一天。 时间间隔以天为单位来衡量一致性,因为以较大时间单位表示的天数(如月和年)会有所不同。

对象的值 TimeSpan 是等于表示的时间间隔的刻度数。 时钟周期等于 100 纳秒,即 1000 万分之一秒。 对象的值 TimeSpan 范围 TimeSpan.MinValue 可以从 到 TimeSpan.MaxValue

实例化 TimeSpan 值

可以通过多种方式实例化 TimeSpan 值:

  • 通过调用其隐式无参数构造函数。 这将创建一个值为 TimeSpan.Zero的对象,如以下示例所示。

    TimeSpan interval = new TimeSpan();
    Console.WriteLine(interval.Equals(TimeSpan.Zero));    // Displays "True".
    
    let interval = TimeSpan()
    printfn $"{interval.Equals TimeSpan.Zero}"    // Displays "True".
    
    Dim interval As New TimeSpan()
    Console.WriteLine(interval.Equals(TimeSpan.Zero))     ' Displays "True".
    
  • 通过调用其显式构造函数之一。 以下示例将值 TimeSpan 初始化为指定的小时数、分钟数和秒数。

    TimeSpan interval = new TimeSpan(2, 14, 18);
    Console.WriteLine(interval.ToString());              
    
    // Displays "02:14:18".
    
    let interval = TimeSpan(2, 14, 18)
    printfn $"{interval}"              
    
    // Displays "02:14:18".
    
    Dim interval As New TimeSpan(2, 14, 18)
    Console.WriteLine(interval.ToString())                ' Displays "02:14:18".
    
  • 通过调用 方法或执行返回 TimeSpan 值的操作。 例如,可以实例化表示两个 TimeSpan 日期和时间值之间的间隔的值,如以下示例所示。

    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
    
    let departure = DateTime(2010, 6, 12, 18, 32, 0)
    let arrival = DateTime(2010, 6, 13, 22, 47, 0)
    let travelTime = arrival - departure  
    printfn $"{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
    
    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
    

    还可以通过这种方式将 对象初始化 TimeSpan 为零时间值,如以下示例所示。

       Random rnd = new Random();
    
       TimeSpan timeSpent = TimeSpan.Zero;
    
       timeSpent += GetTimeBeforeLunch();
       timeSpent += GetTimeAfterLunch();
    
       Console.WriteLine("Total time: {0}", timeSpent);
    
       TimeSpan GetTimeBeforeLunch()
       {
          return new TimeSpan(rnd.Next(3, 6), 0, 0);
       }
       
       TimeSpan GetTimeAfterLunch()
       {
          return new TimeSpan(rnd.Next(3, 6), 0, 0);
       }
    
       // The example displays output like the following:
       //        Total time: 08:00:00
    
    open System
    
    let rnd = Random()
    
    let getTimeBeforeLunch () =
        TimeSpan(rnd.Next(3, 6), 0, 0)
    
    let getTimeAfterLunch() =
        TimeSpan(rnd.Next(3, 6), 0, 0)
    
    do
        let timeSpent = TimeSpan.Zero
    
        let timeSpent = timeSpent + getTimeBeforeLunch ()
        let timeSpent = timeSpent + getTimeAfterLunch ()
    
        printfn $"Total time: {timeSpent}"
    
    
    // The example displays output like the following:
    //        Total time: 08:00:00
    
    Module Example
       Dim rnd As New Random()
       
       Public Sub Main()
          Dim timeSpent As TimeSpan = TimeSpan.Zero
    
          timeSpent += GetTimeBeforeLunch()
          timeSpent += GetTimeAfterLunch()
    
          Console.WriteLine("Total time: {0}", timeSpent)
       End Sub
       
       Private Function GetTimeBeforeLunch() As TimeSpan
          Return New TimeSpan(rnd.Next(3, 6), 0, 0)
       End Function
       
       Private Function GetTimeAfterLunch() As TimeSpan
          Return New TimeSpan(rnd.Next(3, 6), 0, 0)
       End Function
    End Module
    ' The example displays output like the following:
    '       Total time: 08:00:00
    

    TimeSpan值由 、 和 结构的算术运算符和TimeSpan方法DateTimeDateTimeOffset返回。

  • 通过分析值的字符串表示形式 TimeSpan 。 可以使用 ParseTryParse 方法将包含时间间隔的字符串转换为 TimeSpan 值。 以下示例使用 Parse 方法将字符串数组转换为 TimeSpan 值。

    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'
    
    let values = [| "12"; "31."; "5.8:32:16"; "12:12:15.95"; ".12" |]
    for value in values do
        try
            let ts = TimeSpan.Parse value
            printfn $"'{value}' --> {ts}"
        with 
        | :? FormatException ->
            printfn $"Unable to parse '{value}'"
        | :? OverflowException ->
            printfn $"'{value}' is outside the range of a TimeSpan."
    
    // 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'
    
    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'
    

    此外,还可以通过调用 ParseExactTryParseExact 方法定义要分析并转换为TimeSpan值的输入字符串的精确格式。

对 TimeSpan 值执行操作

可以使用 和 Subtraction 运算符或通过调用 Add 和 方法来添加和Subtract减去持续时间Addition。 还可以通过调用 CompareCompareToEquals 方法比较两个持续时间。 结构 TimeSpan 还包括 DurationNegate 方法,这些方法将时间间隔转换为正值和负值,

值的范围 TimeSpanMinValueMaxValue

设置 TimeSpan 值的格式

TimeSpan值可以表示为 [-]dhhmmssff,其中可选减号表示负时间间隔,d 分量为天,hh 为小时,以 24 小时制为度量值,mm 为分钟,ss 为秒,ff 为秒的分数。 也就是说,时间间隔由一天中没有时间的正数或负天数组成,或者包含一天中某个时间的天数,或者只包含一天中的一个时间。

从 .NET Framework 4 开始,TimeSpan结构通过方法ToString的重载支持区分区域性的格式,该方法将值转换为TimeSpan其字符串表示形式。 默认TimeSpan.ToString()方法通过使用与以前版本的 .NET Framework 中的返回值相同的固定格式返回时间间隔。 重 TimeSpan.ToString(String) 载允许指定一个格式字符串,用于定义时间间隔的字符串表示形式。 重 TimeSpan.ToString(String, IFormatProvider) 载允许指定格式字符串和区域性,其格式约定用于创建时间间隔的字符串表示形式。 TimeSpan 支持标准和自定义格式字符串。 (有关详细信息,请参阅 标准 TimeSpan 格式字符串自定义 TimeSpan 格式字符串。) 但是,只有标准格式字符串区分区域性。

还原旧版 TimeSpan 格式设置

在某些情况下,在 .NET Framework 3.5 和更早版本中成功设置值格式TimeSpan的代码在 .NET Framework 4 中失败。 这在调用 <TimeSpan_LegacyFormatMode> 元素 方法以使用格式字符串设置值格式 TimeSpan 的代码中最常见。 以下示例成功格式化 TimeSpan .NET Framework 3.5 及更早版本中的值,但在 .NET Framework 4 及更高版本中引发异常。 请注意,它会尝试使用不支持的格式说明符来设置TimeSpan值的格式,.NET Framework 3.5 及更早版本中会忽略该值。

ShowFormattingCode();
// Output from .NET Framework 3.5 and earlier versions:
//       12:30:45
// Output from .NET Framework 4:
//       Invalid Format    

Console.WriteLine("---");

ShowParsingCode();
// Output:
//       000000006 --> 6.00:00:00

void ShowFormattingCode()
{
   TimeSpan interval = new TimeSpan(12, 30, 45);
   string output;
   try {
      output = String.Format("{0:r}", interval);
   }
   catch (FormatException) {
      output = "Invalid Format";
   }
   Console.WriteLine(output);
}

void ShowParsingCode()
{
   string value = "000000006";
   try {
      TimeSpan interval = TimeSpan.Parse(value);
      Console.WriteLine("{0} --> {1}", value, interval);
   }
   catch (FormatException) {
      Console.WriteLine("{0}: Bad Format", value);
   }   
   catch (OverflowException) {
      Console.WriteLine("{0}: Overflow", value);
   }
}
let showFormattingCode () =
    let interval = TimeSpan(12, 30, 45)
    try
        $"{interval:r}"
    with :? FormatException ->
        "Invalid Format"
    |> printfn "%s"

let showParsingCode () =
    let value = "000000006"
    try
        let interval = TimeSpan.Parse value
        printfn $"{value} --> {interval}"
    with
    | :? FormatException ->
        printfn $"{value}: Bad Format"
    | :? OverflowException ->
        printfn $"{value}: Overflow"

showFormattingCode ()
// Output from .NET Framework 3.5 and earlier versions:
//       12:30:45
// Output from .NET Framework 4:
//       Invalid Format    

printfn "---"

showParsingCode ()
// Output:
//       000000006 --> 6.00:00:00
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

如果无法修改代码,可以通过以下方法之一还原值的旧格式设置 TimeSpan

  • 通过创建包含 TimeSpan_LegacyFormatMode 元素的<>配置文件。 将此元素的 enabled 属性设置为 可 true 按应用程序还原旧 TimeSpan 格式。

  • 通过在创建应用程序域时设置“NetFx40_TimeSpanLegacyFormatMode”兼容性开关。 这可以基于每个应用程序域启用旧 TimeSpan 格式设置。 以下示例创建使用旧格式 TimeSpan 设置的应用程序域。

    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");
       }
    }
    
    open System
    
    let appSetup = AppDomainSetup()
    appSetup.SetCompatibilitySwitches [| "NetFx40_TimeSpanLegacyFormatMode" |]
    let legacyDomain = AppDomain.CreateDomain("legacyDomain", null, appSetup)
    legacyDomain.ExecuteAssembly "ShowTimeSpan.exe" |> ignore
    
    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
    

    当以下代码在新应用程序域中执行时,它将还原为旧 TimeSpan 格式设置行为。

    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.
    
    open System
    
    let interval = DateTime.Now - DateTime.Now.Date
    printfn $"Elapsed Time Today: {interval:d} hours."
    // The example displays the following output:
    //       Elapsed Time Today: 01:40:52.2524662 hours.
    
    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.
    

构造函数

TimeSpan(Int32, Int32, Int32)

TimeSpan 结构的新实例初始化为指定的小时数、分钟数和秒数。

TimeSpan(Int32, Int32, Int32, Int32)

TimeSpan 结构的新实例初始化为指定的天数、小时数、分钟数和秒数。

TimeSpan(Int32, Int32, Int32, Int32, Int32)

TimeSpan 结构的新实例初始化为指定的天数、小时数、分钟数、秒数和毫秒数。

TimeSpan(Int32, Int32, Int32, Int32, Int32, Int32)

将 结构的新实例 TimeSpan 初始化为指定的天数、小时数、分钟数、秒数、毫秒数和微秒数。

TimeSpan(Int64)

TimeSpan 结构的新实例初始化为指定的刻度数。

字段

MaxValue

表示最大的 TimeSpan 值。 此字段为只读。

MinValue

表示最小的 TimeSpan 值。 此字段为只读。

NanosecondsPerTick

表示每刻度数的纳秒数。 此字段为常数。

TicksPerDay

表示一天中的刻度数。 此字段为常数。

TicksPerHour

表示 1 小时的刻度数。 此字段为常数。

TicksPerMicrosecond

表示以 1 微秒为单位的刻度数。 此字段为常数。

TicksPerMillisecond

表示 1 毫秒的刻度数。 此字段为常数。

TicksPerMinute

表示 1 分钟的刻度数。 此字段为常数。

TicksPerSecond

表示 1 秒的刻度数。

Zero

表示零 TimeSpan 值。 此字段为只读。

属性

Days

获取当前 TimeSpan 结构所表示的时间间隔的天数部分。

Hours

获取当前 TimeSpan 结构所表示的时间间隔的小时数部分。

Microseconds

获取当前 TimeSpan 结构表示的时间间隔的微秒分量。

Milliseconds

获取当前 TimeSpan 结构所表示的时间间隔的毫秒数部分。

Minutes

获取当前 TimeSpan 结构所表示的时间间隔的分钟数部分。

Nanoseconds

获取由当前 TimeSpan 结构表示的时间间隔的纳秒分量。

Seconds

获取当前 TimeSpan 结构所表示的时间间隔的秒数部分。

Ticks

获取表示当前 TimeSpan 结构的值的刻度数。

TotalDays

获取以整天数和天的小数部分表示的当前 TimeSpan 结构的值。

TotalHours

获取以整小时数和小时的小数部分表示的当前 TimeSpan 结构的值。

TotalMicroseconds

获取以整微秒和小数微秒表示的当前 TimeSpan 结构的值。

TotalMilliseconds

获取以整毫秒数和毫秒的小数部分表示的当前 TimeSpan 结构的值。

TotalMinutes

获取以整分钟数和分钟的小数部分表示的当前 TimeSpan 结构的值。

TotalNanoseconds

获取以整数和小数纳秒表示的当前 TimeSpan 结构的值。

TotalSeconds

获取以整秒数和秒的小数部分表示的当前 TimeSpan 结构的值。

方法

Add(TimeSpan)

返回一个新的 TimeSpan 对象,其值为指定的 TimeSpan 对象与此实例的值之和。

Compare(TimeSpan, TimeSpan)

比较两个 TimeSpan 值,并返回一个整数,该整数指示第一个值是短于、等于还是长于第二个值。

CompareTo(Object)

将此实例与指定对象进行比较,并返回一个整数,该整数指示此实例是短于、等于还是长于指定对象。

CompareTo(TimeSpan)

将此实例与指定的 TimeSpan 对象进行比较,并返回一个整数,该整数指示此实例是短于、等于还是长于 TimeSpan 对象。

Divide(Double)

返回一个新的 TimeSpan 对象,其值是此实例和指定的 divisor 相除的结果。

Divide(TimeSpan)

返回一个新的 Double 值,该值是此实例和指定的 ts 相除的结果。

Duration()

返回新的 TimeSpan 对象,其值是当前 TimeSpan 对象的绝对值。

Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。

Equals(TimeSpan)

返回一个值,该值指示此实例是否与指定的 TimeSpan 相等。

Equals(TimeSpan, TimeSpan)

返回一个值,该值指示 TimeSpan 的两个指定实例是否相等。

FromDays(Double)

返回表示指定天数的 TimeSpan,其中对天数的指定精确到最接近的毫秒。

FromHours(Double)

返回表示指定小时数的 TimeSpan,其中对小时数的指定精确到最接近的毫秒。

FromMicroseconds(Double)

返回一个 TimeSpan ,它表示指定的微秒数。

FromMilliseconds(Double)

返回表示指定毫秒数的 TimeSpan

FromMinutes(Double)

返回表示指定分钟数的 TimeSpan,其中对分钟数的指定精确到最接近的毫秒。

FromSeconds(Double)

返回表示指定秒数的 TimeSpan,其中对秒数的指定精确到最接近的毫秒。

FromTicks(Int64)

返回表示指定时间的 TimeSpan,其中对时间的指定以刻度为单位。

GetHashCode()

返回此实例的哈希代码。

Multiply(Double)

返回一个新的 TimeSpan 对象,其值是此实例和指定的 factor 相乘的结果。

Negate()

返回一个新的 TimeSpan 对象,它的值为这个实例的相反值。

Parse(ReadOnlySpan<Char>, IFormatProvider)

使用指定的区域性特定格式信息,将时间间隔的范围表示形式转换为其等效的 TimeSpan

Parse(String)

将时间间隔的字符串表示形式转换为等效的 TimeSpan

Parse(String, IFormatProvider)

使用指定的区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan

ParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpanStyles)

使用指定的格式和区域性特定格式信息,将时间间隔的字符型范围转换为其等效的 TimeSpan。 字符串表示形式的格式必须与指定的格式完全匹配。

ParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpanStyles)

使用指定的格式、区域性特定格式信息和样式,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

ParseExact(String, String, IFormatProvider)

使用指定的格式和区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与指定的格式完全匹配。

ParseExact(String, String, IFormatProvider, TimeSpanStyles)

使用指定的格式、区域性特定格式信息和样式,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与指定的格式完全匹配。

ParseExact(String, String[], IFormatProvider)

使用指定的格式字符串数组和区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

ParseExact(String, String[], IFormatProvider, TimeSpanStyles)

使用指定的格式、区域性特定格式信息和样式,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

Subtract(TimeSpan)

返回一个新的 TimeSpan 对象,其值为指定的 TimeSpan 对象与此实例的值之差。

ToString()

将当前 TimeSpan 对象的值转换为其等效的字符串表示形式。

ToString(String)

使用指定的格式将当前 TimeSpan 对象的值转换为其等效的字符串表示形式。

ToString(String, IFormatProvider)

使用指定的格式和区域性特定的格式设置信息,将当前 TimeSpan 对象的值转换为其等效字符串表示形式。

TryFormat(Span<Byte>, Int32, ReadOnlySpan<Char>, IFormatProvider)

表示一个时间间隔。

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

尝试将当前时间范围数字实例的值设置为所提供的字符范围格式。

TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

使用指定的区域性特定格式设置信息,将时间间隔的范围表示形式转换为其等效的 TimeSpan,并返回一个指示转换是否成功的值。

TryParse(ReadOnlySpan<Char>, TimeSpan)

将时间间隔的范围表示形式转换为其等效的 TimeSpan,并返回一个指示转换是否成功的值。

TryParse(String, IFormatProvider, TimeSpan)

使用指定的区域性特定格式设置信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan,并返回一个指示转换是否成功的值。

TryParse(String, TimeSpan)

将时间间隔的字符串表示形式转换为其等效的 TimeSpan,并返回一个指示转换是否成功的值。

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpan)

使用指定的格式和区域性特定格式信息将时间间隔的指定范围表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与指定的格式完全匹配。

TryParseExact(ReadOnlySpan<Char>, ReadOnlySpan<Char>, IFormatProvider, TimeSpanStyles, TimeSpan)

使用指定的格式、区域性特定格式信息和样式,将时间间隔的指定范围表示形式转换为其等效的 TimeSpan,并返回一个指示转换是否成功的值。 字符串表示形式的格式必须与指定的格式完全匹配。

TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpan)

使用指定的格式和区域性特定格式信息将时间间隔的指定范围表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

TryParseExact(ReadOnlySpan<Char>, String[], IFormatProvider, TimeSpanStyles, TimeSpan)

使用指定的格式、区域性特定格式信息和样式将时间间隔的指定范围表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

TryParseExact(String, String, IFormatProvider, TimeSpan)

使用指定的格式和区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与指定的格式完全匹配。

TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan)

使用指定的格式、区域性特定格式信息和样式,将时间间隔的字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与指定的格式完全匹配。

TryParseExact(String, String[], IFormatProvider, TimeSpan)

使用指定的格式和区域性特定格式信息将时间间隔的指定字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

TryParseExact(String, String[], IFormatProvider, TimeSpanStyles, TimeSpan)

使用指定的格式、区域性特定格式信息和样式将时间间隔的指定字符串表示形式转换为其等效的 TimeSpan。 字符串表示形式的格式必须与一种指定的格式完全匹配。

运算符

Addition(TimeSpan, TimeSpan)

添加两个指定的 TimeSpan 实例。

Division(TimeSpan, Double)

返回一个新的 TimeSpan 对象,其值是 timeSpan 实例和指定的 divisor 相除的结果。

Division(TimeSpan, TimeSpan)

返回一个新的 Double 值,该值是 t1 实例和指定的 t2 相除的结果。

Equality(TimeSpan, TimeSpan)

指示两个 TimeSpan 实例是否相等。

GreaterThan(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否大于另一个指定的 TimeSpan

GreaterThanOrEqual(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否大于或等于另一个指定的 TimeSpan

Inequality(TimeSpan, TimeSpan)

指示两个 TimeSpan 实例是否不相等。

LessThan(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否小于另一个指定的 TimeSpan

LessThanOrEqual(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否小于或等于另一个指定的 TimeSpan

Multiply(Double, TimeSpan)

返回一个新的 TimeSpan 对象,其值是指定的 factor 和指定的 timeSpan 实例的乘积。

Multiply(TimeSpan, Double)

返回一个新的 TimeSpan 对象,其值是指定的 timeSpan 实例和指定的 factor 的乘积。

Subtraction(TimeSpan, TimeSpan)

从另一个指定的 TimeSpan 中减去指定的 TimeSpan

UnaryNegation(TimeSpan)

返回一个 TimeSpan,它的值为这个指定实例的相反值。

UnaryPlus(TimeSpan)

返回指定的 TimeSpan 的实例。

显式接口实现

IComparable.CompareTo(Object)

将此实例与指定对象进行比较,并返回一个整数,该整数指示此实例是短于、等于还是长于指定对象。

适用于

另请参阅