使用日期和时间执行算术运算Performing arithmetic operations with dates and times

DateTime 尽管DateTimeOffset和结构都提供对其值执行算术运算的成员, 但算术运算的结果却非常不同。Although both the DateTime and the DateTimeOffset structures provide members that perform arithmetic operations on their values, the results of arithmetic operations are very different. 本主题将探讨这些差异, 将它们与日期和时间数据中的时区识别度关联起来, 并讨论如何使用日期和时间数据执行完全时区感知操作。This topic examines those differences, relates them to degrees of time zone awareness in date and time data, and discusses how to perform fully time zone aware operations using date and time data.

日期时间值的比较和算术运算Comparisons and arithmetic operations with DateTime values

DateTime.Kind属性允许将值分配给日期和时间,以指示它是表示本地时间、协调世界时(UTC)还是未指定的时区DateTimeKind中的时间。The DateTime.Kind property allows a DateTimeKind value to be assigned to the date and time to indicate whether it represents local time, Coordinated Universal Time (UTC), or the time in an unspecified time zone. 但是, 在对DateTimeKind值进行比较或执行日期和时间算法时, 会忽略此有限的时区信息。However, this limited time zone information is ignored when comparing or performing date and time arithmetic on DateTimeKind values. 以下示例通过比较当前本地时间与当前 UTC 时间,对此进行了阐释。The following example, which compares the current local time with the current UTC time, illustrates this.

using System;

public enum TimeComparison
{
   EarlierThan = -1,
   TheSameAs = 0,
   LaterThan = 1
}

public class DateManipulation
{
   public static void Main()
   {
      DateTime localTime = DateTime.Now;
      DateTime utcTime = DateTime.UtcNow;
      
      Console.WriteLine("Difference between {0} and {1} time: {2}:{3} hours", 
                        localTime.Kind.ToString(), 
                        utcTime.Kind.ToString(), 
                        (localTime - utcTime).Hours, 
                        (localTime - utcTime).Minutes);
      Console.WriteLine("The {0} time is {1} the {2} time.", 
                        localTime.Kind.ToString(), 
                        Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime)), 
                        utcTime.Kind.ToString());  
   }
}
// If run in the U.S. Pacific Standard Time zone, the example displays 
// the following output to the console:
//    Difference between Local and Utc time: -7:0 hours
//    The Local time is EarlierThan the Utc time.                                                    
Public Enum TimeComparison As Integer
   EarlierThan = -1
   TheSameAs = 0
   LaterThan = 1
End Enum

Module DateManipulation
   Public Sub Main()
      Dim localTime As Date = Date.Now
      Dim utcTime As Date = Date.UtcNow
      
      Console.WriteLine("Difference between {0} and {1} time: {2}:{3} hours", _
                        localTime.Kind.ToString(), _
                        utcTime.Kind.ToString(), _
                        (localTime - utcTime).Hours, _
                        (localTime - utcTime).Minutes)
      Console.WriteLine("The {0} time is {1} the {2} time.", _
                        localTime.Kind.ToString(), _ 
                        [Enum].GetName(GetType(TimeComparison), localTime.CompareTo(utcTime)), _
                        utcTime.Kind.ToString())  
      ' If run in the U.S. Pacific Standard Time zone, the example displays 
      ' the following output to the console:
      '    Difference between Local and Utc time: -7:0 hours
      '    The Local time is EarlierThan the Utc time.                                                    
   End Sub
End Module

CompareTo(DateTime)方法报告本地时间早于 (或小于) UTC 时间, 并且减法运算指示在美国英语版本中, 系统的 utc 时间和本地时间之间的时差其 UTC 时间与本地时间之间的时差是 7 小时。The CompareTo(DateTime) method reports that the local time is earlier than (or less than) the UTC time, and the subtraction operation indicates that the difference between UTC and the local time for a system in the U.S. Pacific Standard Time zone is seven hours. 但由于这两个值提供的单个时间点的表现形式有所不同,因此从本例中可清楚得知,此时间间隔完全是由本地时区与 UTC 之间的时差所致。But because these two values provide different representations of a single point in time, it is clear in this case that this time interval is completely attributable to the local time zone's offset from UTC.

通常, DateTime.Kind属性不会影响由Kind比较和算术方法返回的结果 (如两个相同时间点的比较指示), 尽管它可能会影响对这些结果的解释。More generally, the DateTime.Kind property does not affect the results returned by Kind comparison and arithmetic methods (as the comparison of two identical points in time indicates), although it can affect the interpretation of those results. 例如:For example:

  • 对两个日期和时间值DateTime.Kind执行的任何算术运算的结果都相等DateTimeKind , 这两个值的属性都反映了两个值之间的实际时间间隔。The result of any arithmetic operation performed on two date and time values whose DateTime.Kind properties both equal DateTimeKind reflects the actual time interval between the two values. 同样,对两个日期和时间值进行比较可精确反映出时间之间的关系。Similarly, the comparison of two such date and time values accurately reflects the relationship between times.

  • 对两个日期和时间值执行的算术或比较运算的结果, DateTime.Kind在两个DateTimeKind日期和时间值上, 两个日期DateTime.Kind和时间值的属性都具有不同的属性值, 这反映了时钟时间的差异介于两个值之间。The result of any arithmetic or comparison operation performed on two date and time values whose DateTime.Kind properties both equal DateTimeKind or on two date and time values with different DateTime.Kind property values reflects the difference in clock time between the two values.

  • 对本地日期和时间值执行的算术或比较运算不考虑某个特定值是否不明确或无效,也不考虑任何调整规则(因本地时区与夏令时的来回转换)的影响。Arithmetic or comparison operations on local date and time values do not consider whether a particular value is ambiguous or invalid, nor do they take account of the effect of any adjustment rules that result from the local time zone's transition to or from daylight saving time.

  • 任何比较或计算 UTC 与本地时间之差的运算所得出的结果中都包含一个时间间隔,它等于本地时区与 UTC 之间的时差。Any operation that compares or calculates the difference between UTC and a local time includes a time interval equal to the local time zone's offset from UTC in the result.

  • 任何比较或计算未指定时间与 UTC 或本地时间的运算都反映简单的时钟时间。Any operation that compares or calculates the difference between an unspecified time and either UTC or the local time reflects simple clock time. 时区差异未纳入考虑范围,且结果不会反映是否应用了时区调整规则。Time zone differences are not considered, and the result does not reflect the application of time zone adjustment rules.

  • 任何比较或计算两个未指定时间之差的运算都可能包含一个未知间隔,它反映两个不同时区内的时间之差。Any operation that compares or calculates the difference between two unspecified times may include an unknown interval that reflects the difference between the time in two different time zones.

在许多情况下, 时区差异不会影响日期和时间计算 (有关其中一些的讨论, 请参阅在DateTime、DateTimeOffset、TimeSpan 和 TimeZoneInfo 之间进行选择), 或日期和时间数据的上下文定义比较或算术运算的含义。There are many scenarios in which time zone differences do not affect date and time calculations (for a discussion of some of these, see Choosing between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo) or in which the context of the date and time data defines the meaning of comparison or arithmetic operations.

具有 DateTimeOffset 值的比较和算术运算Comparisons and arithmetic operations with DateTimeOffset values

DateTimeOffset值不仅包括日期和时间, 还包括明确定义相对于 UTC 的日期和时间的偏移量。A DateTimeOffset value includes not only a date and time, but also an offset that unambiguously defines that date and time relative to UTC. 这样就可以定义与值稍有不同的DateTimeOffset相等性。This makes it possible to define equality somewhat differently than for DateTimeOffset values. 当值相同时, 如果它们具有相同的日期和时间值DateTimeOffset , 则值相等; 如果两个值都引用同一时间点, 则值相等。 DateTimeWhereas DateTime values are equal if they have the same date and time value, DateTimeOffset values are equal if they both refer to the same point in time. 这使得DateTimeOffset在比较中使用的值和大多数算术运算 (用于确定两个日期和时间之间的间隔) 的情况下, 该值更准确且更少。This makes a DateTimeOffset value more accurate and less in need of interpretation when used in comparisons and in most arithmetic operations that determine the interval between two dates and times. 下面的示例 ( DateTimeOffset相当于比较了本地值和 UTC DateTimeOffset值的上一个示例) 演示了这种行为上的差异。The following example, which is the DateTimeOffset equivalent to the previous example that compared local and UTC DateTimeOffset values, illustrates this difference in behavior.

using System;

public enum TimeComparison
{
   EarlierThan = -1,
   TheSameAs = 0,
   LaterThan = 1
}

public class DateTimeOffsetManipulation
{
   public static void Main()
   {
      DateTimeOffset localTime = DateTimeOffset.Now;
      DateTimeOffset utcTime = DateTimeOffset.UtcNow;
      
      Console.WriteLine("Difference between local time and UTC: {0}:{1:D2} hours", 
                        (localTime - utcTime).Hours, 
                        (localTime - utcTime).Minutes);
      Console.WriteLine("The local time is {0} UTC.", 
                        Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime)));  
   }
}
// Regardless of the local time zone, the example displays 
// the following output to the console:
//    Difference between local time and UTC: 0:00 hours.
//    The local time is TheSameAs UTC.
Public Enum TimeComparison As Integer
   EarlierThan = -1
   TheSameAs = 0
   LaterThan = 1
End Enum

Module DateTimeOffsetManipulation
   Public Sub Main()
      Dim localTime As DateTimeOffset = DateTimeOffset.Now
      Dim utcTime As DateTimeOffset = DateTimeOffset.UtcNow
      
      Console.WriteLine("Difference between local time and UTC: {0}:{1:D2} hours.", _
                        (localTime - utcTime).Hours, _
                        (localTime - utcTime).Minutes)
      Console.WriteLine("The local time is {0} UTC.", _
                        [Enum].GetName(GetType(TimeComparison), localTime.CompareTo(utcTime)))  
   End Sub
End Module
' Regardless of the local time zone, the example displays 
' the following output to the console:
'    Difference between local time and UTC: 0:00 hours.
'    The local time is TheSameAs UTC.
'          Console.WriteLine(e.GetType().Name)

在此示例中, CompareTo方法指示当前本地时间和当前 UTC 时间相等, 并且CompareTo(DateTimeOffset)值的减法指示这两个时间之间的差异是TimeSpan.ZeroIn this example, the CompareTo method indicates that the current local time and the current UTC time are equal, and subtraction of CompareTo(DateTimeOffset) values indicates that the difference between the two times is TimeSpan.Zero.

在日期和时间算法DateTimeOffset中使用值的主要限制在于, 虽然DateTimeOffset值具有一定的时区感知, 但并不是完全时区感知。The chief limitation of using DateTimeOffset values in date and time arithmetic is that although DateTimeOffset values have some time zone awareness, they are not fully time zone aware. 尽管在第一次为DateTimeOffset变量分配值时值的偏移量反映了时区与UTC的偏移量,但此后它将与时区解除关联。DateTimeOffsetAlthough the DateTimeOffset value's offset reflects a time zone's offset from UTC when a DateTimeOffset variable is first assigned a value, it becomes disassociated from the time zone thereafter. 由于不再直接与可识别时间关联,日期和时间间隔的相加和相减将不会考虑时区调整规则。Because it is no longer directly associated with an identifiable time, the addition and subtraction of date and time intervals does not consider a time zone's adjustment rules.

举例说明,美国中部标准时区的夏令时转换发生于To illustrate, the transition to daylight saving time in the U.S. Central Standard Time zone occurs at 2:00 A.M. 2008 年 3 月 9 日凌晨 2:00。on March 9, 2008. 这意味着,向中部标准时间 2008 年 3 月 9 日凌晨 1:30 增加两个半小时的间隔,This means that adding a two and a half hour interval to a Central Standard time of 1:30 A.M. 得出的日期和时间应为on March 9, 2008, should produce a date and time of 5:00 A.M. 2008 年 3 月 9 日凌晨 5:00。on March 9, 2008. 但是,如下面的示例所示,加法运算得出的结果却是However, as the following example shows, the result of the addition is 4:00 A.M. 2008 年 3 月 9 日凌晨 4:00。on March 9, 2008. 请注意,此运算结果并不表示正确的时间点,它也不是我们所关注的时区的时间(也就是说,运算未得出预期的时区时差)。Note that this result of this operation does represent the correct point in time, although it is not the time in the time zone in which we are interested (that is, it does not have the expected time zone offset).

using System;

public class IntervalArithmetic
{
   public static void Main()
   {
      DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0);
      const string tzName = "Central Standard Time";
      TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0);

      // Instantiate DateTimeOffset value to have correct CST offset
      try
      {
         DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, 
                    TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime));
      
         // Add two and a half hours      
         DateTimeOffset centralTime2 = centralTime1.Add(twoAndAHalfHours);
         // Display result
         Console.WriteLine("{0} + {1} hours = {2}", centralTime1, 
                                                    twoAndAHalfHours.ToString(), 
                                                    centralTime2);  
      }
      catch (TimeZoneNotFoundException)
      {
         Console.WriteLine("Unable to retrieve Central Standard Time zone information.");
      }
   }
}
// The example displays the following output to the console:
//    3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 4:00:00 AM -06:00
Module IntervalArithmetic
   Public Sub Main()
      Dim generalTime As Date = #03/09/2008 1:30AM#
      Const tzName As String = "Central Standard Time"
      Dim twoAndAHalfHours As New TimeSpan(2, 30, 0)

      ' Instantiate DateTimeOffset value to have correct CST offset
      Try
         Dim centralTime1 As New DateTimeOffset(generalTime, _
                    TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime))
      
         ' Add two and a half hours      
         Dim centralTime2 As DateTimeOffset = centralTime1.Add(twoAndAHalfHours)
         ' Display result
         Console.WriteLine("{0} + {1} hours = {2}", centralTime1, _
                                                    twoAndAHalfHours.ToString(), _
                                                    centralTime2)   
      Catch e As TimeZoneNotFoundException
         Console.WriteLine("Unable to retrieve Central Standard Time zone information.")
      End Try
   End Sub
End Module
' The example displays the following output to the console:
'    3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 4:00:00 AM -06:00

时间区域中时间的算术运算Arithmetic operations with times in time zones

TimeZoneInfo类包括多种转换方法, 这些方法在将时间从一个时区转换到另一个时区时自动应用调整。The TimeZoneInfo class includes a number of conversion methods that automatically apply adjustments when they convert times from one time zone to another. 其中包括:These include the following:

有关详细信息, 请参阅在时区之间转换时间For details, see Converting times between time zones.

在执行日期和时间算术运算时,类不提供任何可自动应用调整规则的方法。ConvertTimeToUtc(DateTime)The ConvertTimeToUtc(DateTime) class does not provide any methods that automatically apply adjustment rules when you perform date and time arithmetic. 但是可以通过将某一时区内的时间转换为 UTC,执行算术运算,然后再将 UTC 转换回该时区内的时间,来实现此目的。However, you can do this by converting the time in a time zone to UTC, performing the arithmetic operation, and then converting from UTC back to the time in the time zone. 有关详细信息,请参阅如何:在日期和时间算法中使用时区。For details, see How to: Use time zones in date and time arithmetic.

例如,以下代码类似于之前向 2008 年 3 月 9 日凌晨 2:00 增加For example, the following code is similar to the previous code that added two-and-a-half hours to 2:00 A.M. 两个半小时的代码。on March 9, 2008. 但是,由于其在执行日期和时间算术前将中部标准时间转换为 UTC,然后将 UTC 结果转换回中部标准时间,所以得出的时间反映的是中部标准时区转换为夏令时。However, because it converts a Central Standard time to UTC before it performs date and time arithmetic, and then converts the result from UTC back to Central Standard time, the resulting time reflects the Central Standard Time Zone's transition to daylight saving time.

using System;

public class TimeZoneAwareArithmetic
{
   public static void Main()
   {
      const string tzName = "Central Standard Time";
      
      DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0);
      TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName);
      TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0);

      // Instantiate DateTimeOffset value to have correct CST offset
      try
      {
         DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, 
                                       cst.GetUtcOffset(generalTime));
      
         // Add two and a half hours
         DateTimeOffset utcTime = centralTime1.ToUniversalTime();
         utcTime += twoAndAHalfHours;
               
         DateTimeOffset centralTime2 = TimeZoneInfo.ConvertTime(utcTime, cst);
         // Display result
         Console.WriteLine("{0} + {1} hours = {2}", centralTime1, 
                                                    twoAndAHalfHours.ToString(), 
                                                    centralTime2);  
      }
      catch (TimeZoneNotFoundException)
      {
         Console.WriteLine("Unable to retrieve Central Standard Time zone information.");
      }
   }
}
// The example displays the following output to the console:
//    3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 5:00:00 AM -05:00
Module TimeZoneAwareArithmetic
   Public Sub Main()
      Const tzName As String = "Central Standard Time"
      
      Dim generalTime As Date = #03/09/2008 1:30AM#
      Dim cst As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(tzName) 
      Dim twoAndAHalfHours As New TimeSpan(2, 30, 0)

      ' Instantiate DateTimeOffset value to have correct CST offset
      Try
         Dim centralTime1 As New DateTimeOffset(generalTime, _
                    cst.GetUtcOffset(generalTime))
      
         ' Add two and a half hours 
         Dim utcTime As DateTimeOffset = centralTime1.ToUniversalTime()
         utcTime += twoAndAHalfHours
         
         Dim centralTime2 As DateTimeOffset = TimeZoneInfo.ConvertTime(utcTime, cst)
         ' Display result
         Console.WriteLine("{0} + {1} hours = {2}", centralTime1, _
                                                    twoAndAHalfHours.ToString(), _
                                                    centralTime2)   
      Catch e As TimeZoneNotFoundException
         Console.WriteLine("Unable to retrieve Central Standard Time zone information.")
      End Try
   End Sub
End Module
' The example displays the following output to the console:
'    3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 5:00:00 AM -05:00

请参阅See also