TimeSpan TimeSpan TimeSpan TimeSpan Struct

Definition

表示一个时间间隔。 Represents a time interval.

public value class TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
type TimeSpan = struct
    interface IFormattable
Public Structure TimeSpan
Implements IComparable, IComparable(Of TimeSpan), IEquatable(Of TimeSpan), IFormattable
Inheritance
Attributes
ComVisibleAttribute SerializableAttribute
Implements

Examples

下面的示例实例化TimeSpan对象,表示两个日期之间的差异。The following example instantiates a TimeSpan object that represents the difference between two dates. 然后,它显示TimeSpan对象的属性。It then displays the TimeSpan object's properties.

// 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
' 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
#>

Remarks

一个TimeSpan对象都表示一个时间间隔 (持续时间的时间或时间),单位为正数或负数的天数、 小时、 分钟、 秒和小数部分的第二个数字。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. TimeSpan结构还可以用于表示一天时间,但仅,如果与某一特定日期无关的时间。The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. 否则为DateTimeDateTimeOffset应改为使用结构。Otherwise, the DateTime or DateTimeOffset structure should be used instead. (有关使用详细信息TimeSpan结构,以反映一天的时间,请参阅选择之间 DateTime、 DateTimeOffset、 TimeSpan 和 TimeZoneInfo。)(For more information about using the TimeSpan structure to reflect the time of day, see Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo.)

备注

一个TimeSpan值表示时间间隔,并且可以表示为特定数目的天数、 小时、 分钟、 秒和毫秒。A TimeSpan value represents a time interval and can be expressed as a particular number of days, hours, minutes, seconds, and milliseconds. 因为它表示常规间隔,而无需引用特定的开始或结束点,则不能将其表示年和月,两者都具有可变数量的天方面。Because it represents a general interval without reference to a particular start or end point, it cannot be expressed in terms of years and months, both of which have a variable number of days. 它不同于DateTime值,该值表示日期和时间,而无需引用特定时区,或DateTimeOffset值,该值表示某个特定时刻的时间。It differs from a DateTime value, which represents a date and time without reference to a particular time zone, or a DateTimeOffset value, which represents a specific moment of time.

最大单元时间TimeSpan结构使用的度量持续时间为一天。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.

TimeSpan对象是等于所表示的时间间隔的计时周期数。The value of a TimeSpan object is the number of ticks that equal the represented time interval. 时钟周期等于 100 纳秒或秒的一千万分之一。A tick is equal to 100 nanoseconds, or one ten-millionth of a second. TimeSpan对象的范围可以从TimeSpan.MinValueTimeSpan.MaxValueThe value of a TimeSpan object can range from TimeSpan.MinValue to TimeSpan.MaxValue.

实例化一个 TimeSpan 值Instantiating a TimeSpan Value

可以实例化TimeSpan中通过多种方式的值:You can instantiate a TimeSpan value in a number of ways:

  • 通过调用其隐式默认构造函数。By calling its implicit default constructor. 这将创建一个对象,其值为TimeSpan.Zero,如下面的示例所示。This creates an object whose value is TimeSpan.Zero, as the following example shows.

    TimeSpan interval = new TimeSpan();
    Console.WriteLine(interval.Equals(TimeSpan.Zero));    // Displays "True".
    
    Dim interval As New TimeSpan()
    Console.WriteLine(interval.Equals(TimeSpan.Zero))     ' Displays "True".
    
  • 通过调用其显式构造函数之一。By calling one of its explicit constructors. 下面的示例初始化TimeSpan为指定的小时、 分钟和秒数的值。The following example initializes a TimeSpan value to a specified number of hours, minutes, and seconds.

    TimeSpan interval = new TimeSpan(2, 14, 18);
    Console.WriteLine(interval.ToString());              // Displays "02:14:18".
    
    Dim interval As New TimeSpan(2, 14, 18)
    Console.WriteLine(interval.ToString())                ' Displays "02:14:18".
    
  • 通过调用方法或执行返回的操作TimeSpan值。By calling a method or performing an operation that returns a TimeSpan value. 例如,您可以实例化TimeSpan值,该值表示两个日期和时间值,如以下示例所示的时间间隔。For example, you can instantiate a TimeSpan value that represents the interval between two date and time values, as the following example shows.

    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
    
    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中这种方式,如以下示例所示的零个时间值的对象。You can also initialize a TimeSpan object to a zero time value in this way, as the following example shows.

    using System;
    
    public class Example
    {
       static Random rnd = new Random();
       
       public static void Main()
       {
          TimeSpan timeSpent = TimeSpan.Zero;
    
          timeSpent += GetTimeBeforeLunch();
          timeSpent += GetTimeAfterLunch();
    
          Console.WriteLine("Total time: {0}", timeSpent);
       }
    
       private static TimeSpan GetTimeBeforeLunch()
       {
          return new TimeSpan(rnd.Next(3, 6), 0, 0);
       }
       
       private static TimeSpan GetTimeAfterLunch()
       {
          return new TimeSpan(rnd.Next(3, 6), 0, 0);
       }
    }
    // 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 算术运算符和方法的返回值DateTimeDateTimeOffset,和TimeSpan结构。TimeSpan values are returned by arithmetic operators and methods of the DateTime, DateTimeOffset, and TimeSpan structures.

  • 通过分析的字符串表示形式TimeSpan值。By parsing the string representation of a TimeSpan value. 可以使用ParseTryParse方法以将包含到的时间间隔的字符串转换TimeSpan值。You can use the Parse and TryParse methods to convert strings that contain time intervals to TimeSpan values. 下面的示例使用Parse方法将字符串转换为数组转换为TimeSpan值。The following example uses the Parse method to convert an array of strings to TimeSpan values.

    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'  
    
    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'  
    

    此外,可以定义要分析并转换为的输入字符串的确切格式TimeSpan值通过调用ParseExactTryParseExact方法。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.

对 TimeSpan 值执行操作Performing Operations on TimeSpan Values

可以添加或减少持续时间是通过AdditionSubtraction运算符,或通过调用AddSubtract方法。You can add and subtract time durations either by using the Addition and Subtraction operators, or by calling the Add and Subtract methods. 此外可以通过调用来比较两个持续时间CompareCompareTo,和Equals方法。You can also compare two time durations by calling the Compare, CompareTo, and Equals methods. TimeSpan结构还包括DurationNegate方法,将时间间隔转换为正值和负值,The TimeSpan structure also includes the Duration and Negate methods, which convert time intervals to positive and negative values,

范围TimeSpan值是MinValueMaxValueThe range of TimeSpan values is MinValue to MaxValue.

设置一个 TimeSpan 值的格式Formatting a TimeSpan Value

一个TimeSpan的值可以表示为 [-]dhh:mm:ssff,其中可选负号指示负时间间隔d分量表示天, hh表示小时采用 24 小时制, mm为分钟, ss为秒,和ff为秒小数部分的第二个。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.

开头.NET Framework 4.NET Framework 4,则TimeSpan结构支持区分区域性的格式通过重载其ToString方法,它将转换TimeSpan为其字符串表示形式的值。Beginning with the .NET Framework 4.NET Framework 4, the TimeSpan structure supports culture-sensitive formatting through the overloads of its ToString method, which converts a TimeSpan value to its string representation. 默认值TimeSpan.ToString()方法通过使用等同于它在以前版本的.NET Framework 的返回值的固定格式返回时间间隔。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. TimeSpan.ToString(String)重载允许您指定一个格式字符串,定义的时间间隔的字符串表示形式。The TimeSpan.ToString(String) overload lets you specify a format string that defines the string representation of the time interval. TimeSpan.ToString(String, IFormatProvider)重载允许您指定一个格式字符串,其格式设置约定用于创建时间间隔的字符串表示形式的区域性。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 支持这两个标准和自定义格式字符串。TimeSpan supports both standard and custom format strings. (有关详细信息,请参阅标准 TimeSpan 格式字符串自定义 TimeSpan 格式字符串。)但是,只有标准格式字符串是区分区域性的。(For more information, see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.) However, only standard format strings are culture-sensitive.

还原旧版 TimeSpan 格式设置Restoring Legacy TimeSpan Formatting

在某些情况下,代码中的成功格式TimeSpan中的值以.NET Framework 3.5.NET Framework 3.5早期版本中的失败和.NET Framework 4.NET Framework 4In some cases, code that successfully formats TimeSpan values in .NET Framework 3.5.NET Framework 3.5 and earlier versions fails in .NET Framework 4.NET Framework 4. 这是在代码中调用的最常见< TimeSpan_LegacyFormatMode > 元素方法来设置格式TimeSpan有一个格式字符串的值。This is most common in code that calls a <TimeSpan_LegacyFormatMode> element method to format a TimeSpan value with a format string. 下面的示例成功设置TimeSpan中的值.NET Framework 3.5.NET Framework 3.5及更早版本,但在引发异常.NET Framework 4.NET Framework 4及更高版本。The following example successfully formats a TimeSpan value in .NET Framework 3.5.NET Framework 3.5 and earlier versions, but throws an exception in .NET Framework 4.NET Framework 4 and later versions. 请注意,它会尝试设置的格式TimeSpan通过使用不受支持的格式说明符,在将被忽略的值.NET Framework 3.5.NET Framework 3.5及更早版本。Note that it attempts to format a TimeSpan value by using an unsupported format specifier, which is ignored in .NET Framework 3.5.NET Framework 3.5 and earlier versions.

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
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中通过以下方式之一的值:If you cannot modify the code, you can restore the legacy formatting of TimeSpan values in one of the following ways:

  • 通过创建配置文件包含< TimeSpan_LegacyFormatMode > 元素By creating a configuration file that contains the <TimeSpan_LegacyFormatMode> element. 设置此元素的enabled归于true恢复旧TimeSpan基于每个应用程序格式设置。Setting this element's enabled attribute to true restores legacy TimeSpan formatting on a per-application basis.

  • 通过设置"NetFx40_TimeSpanLegacyFormatMode"兼容性切换时创建应用程序域。By setting the "NetFx40_TimeSpanLegacyFormatMode" compatibility switch when you create an application domain. 这将启用旧TimeSpan设置每个应用程序域基础上的格式。This enables legacy TimeSpan formatting on a per-application-domain basis. 下面的示例创建使用应用程序域旧TimeSpan格式设置。The following example creates an application domain that uses legacy TimeSpan formatting.

    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");
       }
    }
    
    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格式设置行为。When the following code executes in the new application domain, it reverts to legacy TimeSpan formatting behavior.

    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.
    
    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.
    

Constructors

TimeSpan(Int64) TimeSpan(Int64) TimeSpan(Int64) TimeSpan(Int64)

TimeSpan 结构的新实例初始化为指定的刻度数。 Initializes a new instance of the TimeSpan structure to the specified number of ticks.

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

TimeSpan 结构的新实例初始化为指定的小时数、分钟数和秒数。 Initializes a new instance of the TimeSpan structure to a specified number of hours, minutes, and seconds.

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

TimeSpan 结构的新实例初始化为指定的天数、小时数、分钟数和秒数。 Initializes a new instance of the TimeSpan structure to a specified number of days, hours, minutes, and seconds.

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

TimeSpan 结构的新实例初始化为指定的天数、小时数、分钟数、秒数和毫秒数。 Initializes a new instance of the TimeSpan structure to a specified number of days, hours, minutes, seconds, and milliseconds.

Fields

MaxValue MaxValue MaxValue MaxValue

表示最大的 TimeSpan 值。 Represents the maximum TimeSpan value. 此字段为只读。 This field is read-only.

MinValue MinValue MinValue MinValue

表示最小的 TimeSpan 值。 Represents the minimum TimeSpan value. 此字段为只读。 This field is read-only.

TicksPerDay TicksPerDay TicksPerDay TicksPerDay

表示一天中的刻度数。 Represents the number of ticks in 1 day. 此字段为常数。 This field is constant.

TicksPerHour TicksPerHour TicksPerHour TicksPerHour

表示 1 小时的刻度数。 Represents the number of ticks in 1 hour. 此字段为常数。 This field is constant.

TicksPerMillisecond TicksPerMillisecond TicksPerMillisecond TicksPerMillisecond

表示 1 毫秒的刻度数。 Represents the number of ticks in 1 millisecond. 此字段为常数。 This field is constant.

TicksPerMinute TicksPerMinute TicksPerMinute TicksPerMinute

表示 1 分钟的刻度数。 Represents the number of ticks in 1 minute. 此字段为常数。 This field is constant.

TicksPerSecond TicksPerSecond TicksPerSecond TicksPerSecond

表示 1 秒的刻度数。 Represents the number of ticks in 1 second.

Zero Zero Zero Zero

表示零 TimeSpan 值。 Represents the zero TimeSpan value. 此字段为只读。 This field is read-only.

Properties

Days Days Days Days

获取当前 TimeSpan 结构所表示的时间间隔的天数部分。 Gets the days component of the time interval represented by the current TimeSpan structure.

Hours Hours Hours Hours

获取当前 TimeSpan 结构所表示的时间间隔的小时数部分。 Gets the hours component of the time interval represented by the current TimeSpan structure.

Milliseconds Milliseconds Milliseconds Milliseconds

获取当前 TimeSpan 结构所表示的时间间隔的毫秒数部分。 Gets the milliseconds component of the time interval represented by the current TimeSpan structure.

Minutes Minutes Minutes Minutes

获取当前 TimeSpan 结构所表示的时间间隔的分钟数部分。 Gets the minutes component of the time interval represented by the current TimeSpan structure.

Seconds Seconds Seconds Seconds

获取当前 TimeSpan 结构所表示的时间间隔的秒数部分。 Gets the seconds component of the time interval represented by the current TimeSpan structure.

Ticks Ticks Ticks Ticks

获取表示当前 TimeSpan 结构的值的刻度数。 Gets the number of ticks that represent the value of the current TimeSpan structure.

TotalDays TotalDays TotalDays TotalDays

获取以整天数和天的小数部分表示的当前 TimeSpan 结构的值。 Gets the value of the current TimeSpan structure expressed in whole and fractional days.

TotalHours TotalHours TotalHours TotalHours

获取以整小时数和小时的小数部分表示的当前 TimeSpan 结构的值。 Gets the value of the current TimeSpan structure expressed in whole and fractional hours.

TotalMilliseconds TotalMilliseconds TotalMilliseconds TotalMilliseconds

获取以整毫秒数和毫秒的小数部分表示的当前 TimeSpan 结构的值。 Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.

TotalMinutes TotalMinutes TotalMinutes TotalMinutes

获取以整分钟数和分钟的小数部分表示的当前 TimeSpan 结构的值。 Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

TotalSeconds TotalSeconds TotalSeconds TotalSeconds

获取以整秒数和秒的小数部分表示的当前 TimeSpan 结构的值。 Gets the value of the current TimeSpan structure expressed in whole and fractional seconds.

Methods

Add(TimeSpan) Add(TimeSpan) Add(TimeSpan) Add(TimeSpan)

返回一个新的 TimeSpan 对象,其值为指定的 TimeSpan 对象与此实例的值之和。 Returns a new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance.

Compare(TimeSpan, TimeSpan) Compare(TimeSpan, TimeSpan) Compare(TimeSpan, TimeSpan) Compare(TimeSpan, TimeSpan)

比较两个 TimeSpan 值,并返回一个整数,该整数指示第一个值是短于、等于还是长于第二个值。 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.

CompareTo(Object) CompareTo(Object) CompareTo(Object) 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.

CompareTo(TimeSpan) CompareTo(TimeSpan) CompareTo(TimeSpan) CompareTo(TimeSpan)

将此实例与指定的 TimeSpan 对象进行比较,并返回一个整数,该整数指示此实例是短于、等于还是长于 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.

Divide(TimeSpan) Divide(TimeSpan) Divide(TimeSpan) Divide(TimeSpan)
Divide(Double) Divide(Double) Divide(Double) Divide(Double)
Duration() Duration() Duration() Duration()

返回新的 TimeSpan 对象,其值是当前 TimeSpan 对象的绝对值。 Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。 Returns a value indicating whether this instance is equal to a specified object.

Equals(TimeSpan) Equals(TimeSpan) Equals(TimeSpan) Equals(TimeSpan)

返回一个值,该值指示此实例是否与指定的 TimeSpan 相等。 Returns a value indicating whether this instance is equal to a specified TimeSpan object.

Equals(TimeSpan, TimeSpan) Equals(TimeSpan, TimeSpan) Equals(TimeSpan, TimeSpan) Equals(TimeSpan, TimeSpan)

返回一个值,该值指示 TimeSpan 的两个指定实例是否相等。 Returns a value that indicates whether two specified instances of TimeSpan are equal.

FromDays(Double) FromDays(Double) FromDays(Double) FromDays(Double)

返回表示指定天数的 TimeSpan,其中对天数的指定精确到最接近的毫秒。 Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.

FromHours(Double) FromHours(Double) FromHours(Double) FromHours(Double)

返回表示指定小时数的 TimeSpan,其中对小时数的指定精确到最接近的毫秒。 Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.

FromMilliseconds(Double) FromMilliseconds(Double) FromMilliseconds(Double) FromMilliseconds(Double)

返回表示指定毫秒数的 TimeSpan Returns a TimeSpan that represents a specified number of milliseconds.

FromMinutes(Double) FromMinutes(Double) FromMinutes(Double) FromMinutes(Double)

返回表示指定分钟数的 TimeSpan,其中对分钟数的指定精确到最接近的毫秒。 Returns a TimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond.

FromSeconds(Double) FromSeconds(Double) FromSeconds(Double) FromSeconds(Double)

返回表示指定秒数的 TimeSpan,其中对秒数的指定精确到最接近的毫秒。 Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.

FromTicks(Int64) FromTicks(Int64) FromTicks(Int64) FromTicks(Int64)

返回表示指定时间的 TimeSpan,其中对时间的指定以刻度为单位。 Returns a TimeSpan that represents a specified time, where the specification is in units of ticks.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。 Returns a hash code for this instance.

Multiply(Double) Multiply(Double) Multiply(Double) Multiply(Double)
Negate() Negate() Negate() Negate()

返回一个新的 TimeSpan 对象,它的值为这个实例的相反值。 Returns a new TimeSpan object whose value is the negated value of this instance.

Parse(String) Parse(String) Parse(String) Parse(String)

将时间间隔的字符串表示形式转换为等效的 TimeSpan Converts the string representation of a time interval to its TimeSpan equivalent.

Parse(ReadOnlySpan<Char>, IFormatProvider) Parse(ReadOnlySpan<Char>, IFormatProvider) Parse(ReadOnlySpan<Char>, IFormatProvider) Parse(ReadOnlySpan<Char>, IFormatProvider)
Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

使用指定的区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.

ParseExact(String, String, IFormatProvider, TimeSpanStyles) ParseExact(String, String, IFormatProvider, TimeSpanStyles) ParseExact(String, String, IFormatProvider, TimeSpanStyles) ParseExact(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. 字符串表示形式的格式必须与指定的格式完全匹配。 The format of the string representation must match the specified format exactly.

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

使用指定的格式、区域性特定格式信息和样式,将时间间隔的字符串表示形式转换为其等效的 TimeSpan 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.

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

使用指定的格式字符串数组和区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 TimeSpan 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.

ParseExact(String, String, IFormatProvider) ParseExact(String, String, IFormatProvider) ParseExact(String, String, IFormatProvider) ParseExact(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. 字符串表示形式的格式必须与指定的格式完全匹配。 The format of the string representation must match the specified format exactly.

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

返回一个新的 TimeSpan 对象,其值为指定的 TimeSpan 对象与此实例的值之差。 Returns a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance.

ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider)

使用指定的格式和区域性特定的格式设置信息,将当前 TimeSpan 对象的值转换为其等效字符串表示形式。 Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format and culture-specific formatting information.

ToString(String) ToString(String) ToString(String) ToString(String)

使用指定的格式将当前 TimeSpan 对象的值转换为其等效的字符串表示形式。 Converts the value of the current TimeSpan object to its equivalent string representation by using the specified format.

ToString() ToString() ToString() ToString()

将当前 TimeSpan 对象的值转换为其等效的字符串表示形式。 Converts the value of the current TimeSpan object to its equivalent string representation.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)
TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan) TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan) TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan) TryParse(ReadOnlySpan<Char>, IFormatProvider, TimeSpan)
TryParse(ReadOnlySpan<Char>, TimeSpan) TryParse(ReadOnlySpan<Char>, TimeSpan) TryParse(ReadOnlySpan<Char>, TimeSpan) TryParse(ReadOnlySpan<Char>, TimeSpan)
TryParse(String, TimeSpan) TryParse(String, TimeSpan) TryParse(String, TimeSpan) TryParse(String, TimeSpan)

将时间间隔的字符串表示形式转换为其等效的 TimeSpan,并返回一个指示转换是否成功的值。 Converts the string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

TryParse(String, IFormatProvider, TimeSpan) TryParse(String, IFormatProvider, TimeSpan) TryParse(String, IFormatProvider, TimeSpan) TryParse(String, IFormatProvider, TimeSpan)

使用指定的区域性特定格式设置信息,将时间间隔的字符串表示形式转换为其等效的 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.

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

使用指定的格式、区域性特定格式信息和样式,将时间间隔的字符串表示形式转换为其等效的 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.

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

使用指定的格式和区域性特定格式信息,将时间间隔的指定字符串表示形式转换为其等效的 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.

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

使用指定的格式、区域性特定格式信息和样式,将时间间隔的指定字符串表示形式转换为其等效的 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.

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

使用指定的格式和区域性特定格式信息,将时间间隔的字符串表示形式转换为其等效的 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.

Operators

Addition(TimeSpan, TimeSpan) Addition(TimeSpan, TimeSpan) Addition(TimeSpan, TimeSpan) Addition(TimeSpan, TimeSpan)

添加两个指定的 TimeSpan 实例。 Adds two specified TimeSpan instances.

Division(TimeSpan, TimeSpan) Division(TimeSpan, TimeSpan) Division(TimeSpan, TimeSpan) Division(TimeSpan, TimeSpan)
Division(TimeSpan, Double) Division(TimeSpan, Double) Division(TimeSpan, Double) Division(TimeSpan, Double)
Equality(TimeSpan, TimeSpan) Equality(TimeSpan, TimeSpan) Equality(TimeSpan, TimeSpan) Equality(TimeSpan, TimeSpan)

指示两个 TimeSpan 实例是否相等。 Indicates whether two TimeSpan instances are equal.

GreaterThan(TimeSpan, TimeSpan) GreaterThan(TimeSpan, TimeSpan) GreaterThan(TimeSpan, TimeSpan) GreaterThan(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否大于另一个指定的 TimeSpan Indicates whether a specified TimeSpan is greater than another specified TimeSpan.

GreaterThanOrEqual(TimeSpan, TimeSpan) GreaterThanOrEqual(TimeSpan, TimeSpan) GreaterThanOrEqual(TimeSpan, TimeSpan) GreaterThanOrEqual(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否大于或等于另一个指定的 TimeSpan Indicates whether a specified TimeSpan is greater than or equal to another specified TimeSpan.

Inequality(TimeSpan, TimeSpan) Inequality(TimeSpan, TimeSpan) Inequality(TimeSpan, TimeSpan) Inequality(TimeSpan, TimeSpan)

指示两个 TimeSpan 实例是否不相等。 Indicates whether two TimeSpan instances are not equal.

LessThan(TimeSpan, TimeSpan) LessThan(TimeSpan, TimeSpan) LessThan(TimeSpan, TimeSpan) LessThan(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否小于另一个指定的 TimeSpan Indicates whether a specified TimeSpan is less than another specified TimeSpan.

LessThanOrEqual(TimeSpan, TimeSpan) LessThanOrEqual(TimeSpan, TimeSpan) LessThanOrEqual(TimeSpan, TimeSpan) LessThanOrEqual(TimeSpan, TimeSpan)

指示指定的 TimeSpan 是否小于或等于另一个指定的 TimeSpan Indicates whether a specified TimeSpan is less than or equal to another specified TimeSpan.

Multiply(Double, TimeSpan) Multiply(Double, TimeSpan) Multiply(Double, TimeSpan) Multiply(Double, TimeSpan)
Multiply(TimeSpan, Double) Multiply(TimeSpan, Double) Multiply(TimeSpan, Double) Multiply(TimeSpan, Double)
Subtraction(TimeSpan, TimeSpan) Subtraction(TimeSpan, TimeSpan) Subtraction(TimeSpan, TimeSpan) Subtraction(TimeSpan, TimeSpan)

从另一个指定的 TimeSpan 中减去指定的 TimeSpan Subtracts a specified TimeSpan from another specified TimeSpan.

UnaryNegation(TimeSpan) UnaryNegation(TimeSpan) UnaryNegation(TimeSpan) UnaryNegation(TimeSpan)

返回一个 TimeSpan,它的值为这个指定实例的相反值。 Returns a TimeSpan whose value is the negated value of the specified instance.

UnaryPlus(TimeSpan) UnaryPlus(TimeSpan) UnaryPlus(TimeSpan) UnaryPlus(TimeSpan)

返回指定的 TimeSpan 的实例。 Returns the specified instance of TimeSpan.

Explicit Interface Implementations

IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)

Applies to

See Also