DateTime.ToUniversalTime 方法

定义

将当前 DateTime 对象的值转换为协调世界时 (UTC)。Converts the value of the current DateTime object to Coordinated Universal Time (UTC).

public:
 DateTime ToUniversalTime();
public DateTime ToUniversalTime ();
member this.ToUniversalTime : unit -> DateTime
Public Function ToUniversalTime () As DateTime

返回

一个对象,其 Kind 属性为 Utc,并且其值为等效于当前 DateTime 对象的值的 UTC;如果经转换的值过大以至于不能由 MaxValue 对象表示,则为 DateTime,或者,如果经转换的值过小以至于不能表示为 MinValue 对象,则为 DateTimeAn object whose Kind property is Utc, and whose value is the UTC equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented by a DateTime object.

示例

下面的示例演示 ToUniversalTime 方法。The following example demonstrates the ToUniversalTime method.

using namespace System;

void main()
{
   Console::WriteLine("Enter a date and time.");
   String^ strDateTime = Console::ReadLine();

   DateTime localDateTime, univDateTime;
   try
   {
      localDateTime = DateTime::Parse(strDateTime);
      univDateTime = localDateTime.ToUniversalTime();
    
      Console::WriteLine("{0} local time is {1} universal time.",
                         localDateTime, univDateTime );
   }
   catch (FormatException^) 
   {
      Console::WriteLine("Invalid format.");
      return;
   }

   Console::WriteLine("Enter a date and time in universal time.");
   strDateTime = Console::ReadLine();

   try
   {
      univDateTime = DateTime::Parse(strDateTime);
      localDateTime = univDateTime.ToLocalTime();
  
      Console::WriteLine("{0} universal time is {1} local time.",
                         univDateTime, localDateTime );
   }
   catch (FormatException^) 
   {
      Console::WriteLine("Invalid format.");
      return;
   }
}
// The example displays output like the following when run on a 
// computer whose culture is en-US in the Pacific Standard Time zone:
//     Enter a date and time.
//     12/10/2015 6:18 AM
//     12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
//     Enter a date and time in universal time.
//     12/20/2015 6:42:00
//     12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.
using System;

class Example
{
    static void Main()
    {
        DateTime localDateTime, univDateTime;
        
        Console.WriteLine("Enter a date and time.");
        string strDateTime = Console.ReadLine();

        try {
            localDateTime = DateTime.Parse(strDateTime);
            univDateTime = localDateTime.ToUniversalTime();
    
            Console.WriteLine("{0} local time is {1} universal time.",
                                localDateTime,
                                    univDateTime); 
        }
        catch (FormatException) {
            Console.WriteLine("Invalid format.");
            return;
        }

        Console.WriteLine("Enter a date and time in universal time.");
        strDateTime = Console.ReadLine();

        try {
            univDateTime = DateTime.Parse(strDateTime);
            localDateTime = univDateTime.ToLocalTime();
    
            Console.WriteLine("{0} universal time is {1} local time.",
                                     univDateTime,
                                     localDateTime); 
        }
        catch (FormatException) {
            Console.WriteLine("Invalid format.");
            return;
        }

    }
}
// The example displays output like the following when run on a 
// computer whose culture is en-US in the Pacific Standard Time zone:
//     Enter a date and time.
//     12/10/2015 6:18 AM
//     12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
//     Enter a date and time in universal time.
//     12/20/2015 6:42:00
//     12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.
Module Example
    Sub Main()
      Dim localDateTime, univDateTime As DateTime
      
      Console.WriteLine("Enter a date and time.")
      Dim strDateTime As String = Console.ReadLine()
      Try
         localDateTime = DateTime.Parse(strDateTime)
         univDateTime = localDateTime.ToUniversalTime()
         Console.WriteLine("{0} local time is {1} universal time.", 
                           localDateTime, univDateTime)
      Catch exp As FormatException
         Console.WriteLine("Invalid format.")
      End Try

      Console.WriteLine("Enter a date and time in universal time.")
      strDateTime = Console.ReadLine()
      Try
         univDateTime = DateTime.Parse(strDateTime)
         localDateTime = univDateTime.ToLocalTime()
  
         Console.WriteLine("{0} universal time is {1} local time.", _
                           univDateTime, localDateTime)
      Catch exp As FormatException
         Console.WriteLine("Invalid format.")
      End Try
    End Sub
End Module
' The example displays output like the following when run on a 
' computer whose culture is en-US in the Pacific Standard Time zone:
'     Enter a date and time.
'     12/10/2015 6:18 AM
'     12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
'     Enter a date and time in universal time.
'     12/20/2015 6:42:00
'     12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.

下面的示例使用 SpecifyKind 方法来演示 @no__t 的属性如何影响 @no__t 和 @no__t 转换方法。The following example uses the SpecifyKind method to demonstrate how the Kind property influences the ToLocalTime and ToUniversalTime conversion methods.

// This code example demonstrates the DateTime Kind, Now, and
// UtcNow properties, and the SpecifyKind(), ToLocalTime(), 
// and ToUniversalTime() methods.

using System;

class Sample 
{
    public static void Main() 
    {
// Get the date and time for the current moment, adjusted 
// to the local time zone.

    DateTime saveNow = DateTime.Now;

// Get the date and time for the current moment expressed 
// as coordinated universal time (UTC).

    DateTime saveUtcNow = DateTime.UtcNow;
    DateTime myDt;

// Display the value and Kind property of the current moment 
// expressed as UTC and local time.

    DisplayNow("UtcNow: ..........", saveUtcNow);
    DisplayNow("Now: .............", saveNow);
    Console.WriteLine();

// Change the Kind property of the current moment to 
// DateTimeKind.Utc and display the result.

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Utc);
    Display("Utc: .............", myDt);

// Change the Kind property of the current moment to 
// DateTimeKind.Local and display the result.

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Local);
    Display("Local: ...........", myDt);

// Change the Kind property of the current moment to 
// DateTimeKind.Unspecified and display the result.

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Unspecified);
    Display("Unspecified: .....", myDt);
    }

// Display the value and Kind property of a DateTime structure, the 
// DateTime structure converted to local time, and the DateTime 
// structure converted to universal time. 

    public static string datePatt = @"M/d/yyyy hh:mm:ss tt";
    public static void Display(string title, DateTime inputDt)
    {
    DateTime dispDt = inputDt;
    string dtString;

// Display the original DateTime.

    dtString = dispDt.ToString(datePatt);
    Console.WriteLine("{0} {1}, Kind = {2}", 
                      title, dtString, dispDt.Kind);

// Convert inputDt to local time and display the result. 
// If inputDt.Kind is DateTimeKind.Utc, the conversion is performed.
// If inputDt.Kind is DateTimeKind.Local, the conversion is not performed.
// If inputDt.Kind is DateTimeKind.Unspecified, the conversion is 
// performed as if inputDt was universal time.

    dispDt = inputDt.ToLocalTime();
    dtString = dispDt.ToString(datePatt);
    Console.WriteLine("  ToLocalTime:     {0}, Kind = {1}", 
                      dtString, dispDt.Kind);

// Convert inputDt to universal time and display the result. 
// If inputDt.Kind is DateTimeKind.Utc, the conversion is not performed.
// If inputDt.Kind is DateTimeKind.Local, the conversion is performed.
// If inputDt.Kind is DateTimeKind.Unspecified, the conversion is 
// performed as if inputDt was local time.

    dispDt = inputDt.ToUniversalTime();
    dtString = dispDt.ToString(datePatt);
    Console.WriteLine("  ToUniversalTime: {0}, Kind = {1}", 
                      dtString, dispDt.Kind);
    Console.WriteLine();
    }

// Display the value and Kind property for DateTime.Now and DateTime.UtcNow.

    public static void DisplayNow(string title, DateTime inputDt)
    {
    string dtString = inputDt.ToString(datePatt);
    Console.WriteLine("{0} {1}, Kind = {2}", 
                      title, dtString, inputDt.Kind);
    }
}

/*
This code example produces the following results:

UtcNow: .......... 5/6/2005 09:34:42 PM, Kind = Utc
Now: ............. 5/6/2005 02:34:42 PM, Kind = Local

Utc: ............. 5/6/2005 02:34:42 PM, Kind = Utc
  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
  ToUniversalTime: 5/6/2005 02:34:42 PM, Kind = Utc

Local: ........... 5/6/2005 02:34:42 PM, Kind = Local
  ToLocalTime:     5/6/2005 02:34:42 PM, Kind = Local
  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc

Unspecified: ..... 5/6/2005 02:34:42 PM, Kind = Unspecified
  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc

*/

' This code example demonstrates the DateTime Kind, Now, and
' UtcNow properties, and the SpecifyKind(), ToLocalTime(), 
' and ToUniversalTime() methods.
Class Sample
    Public Shared Sub Main() 
        ' Get the date and time for the current moment, adjusted 
        ' to the local time zone.
        Dim saveNow As DateTime = DateTime.Now
        
        ' Get the date and time for the current moment expressed 
        ' as coordinated universal time (UTC).
        Dim saveUtcNow As DateTime = DateTime.UtcNow
        Dim myDt As DateTime
        
        ' Display the value and Kind property of the current moment 
        ' expressed as UTC and local time.
        DisplayNow("UtcNow: ..........", saveUtcNow)
        DisplayNow("Now: .............", saveNow)
        Console.WriteLine()
        
        ' Change the Kind property of the current moment to 
        ' DateTimeKind.Utc and display the result.
        myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Utc)
        Display("Utc: .............", myDt)
        
        ' Change the Kind property of the current moment to 
        ' DateTimeKind.Local and display the result.
        myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Local)
        Display("Local: ...........", myDt)
        
        ' Change the Kind property of the current moment to 
        ' DateTimeKind.Unspecified and display the result.
        myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Unspecified)
        Display("Unspecified: .....", myDt)
    End Sub
    
    ' Display the value and Kind property of a DateTime structure, the 
    ' DateTime structure converted to local time, and the DateTime 
    ' structure converted to universal time. 

    Public Shared datePatt As String = "M/d/yyyy hh:mm:ss tt"
    
    Public Shared Sub Display(ByVal title As String, ByVal inputDt As DateTime) 
        Dim dispDt As DateTime = inputDt
        Dim dtString As String
        
        ' Display the original DateTime.
        dtString = dispDt.ToString(datePatt)
        Console.WriteLine("{0} {1}, Kind = {2}", title, dtString, dispDt.Kind)
        
        ' Convert inputDt to local time and display the result. 
        ' If inputDt.Kind is DateTimeKind.Utc, the conversion is performed.
        ' If inputDt.Kind is DateTimeKind.Local, the conversion is not performed.
        ' If inputDt.Kind is DateTimeKind.Unspecified, the conversion is 
        ' performed as if inputDt was universal time.
        dispDt = inputDt.ToLocalTime()
        dtString = dispDt.ToString(datePatt)
        Console.WriteLine("  ToLocalTime:     {0}, Kind = {1}", dtString, dispDt.Kind)
        
        ' Convert inputDt to universal time and display the result. 
        ' If inputDt.Kind is DateTimeKind.Utc, the conversion is not performed.
        ' If inputDt.Kind is DateTimeKind.Local, the conversion is performed.
        ' If inputDt.Kind is DateTimeKind.Unspecified, the conversion is 
        ' performed as if inputDt was local time.
        dispDt = inputDt.ToUniversalTime()
        dtString = dispDt.ToString(datePatt)
        Console.WriteLine("  ToUniversalTime: {0}, Kind = {1}", dtString, dispDt.Kind)
        Console.WriteLine()
    End Sub
    
    
    ' Display the value and Kind property for DateTime.Now and DateTime.UtcNow.

    Public Shared Sub DisplayNow(ByVal title As String, ByVal inputDt As DateTime) 
        Dim dtString As String = inputDt.ToString(datePatt)
        Console.WriteLine("{0} {1}, Kind = {2}", title, dtString, inputDt.Kind)
    End Sub
End Class

'
'This code example produces the following results:
'
'UtcNow: .......... 5/6/2005 09:34:42 PM, Kind = Utc
'Now: ............. 5/6/2005 02:34:42 PM, Kind = Local
'
'Utc: ............. 5/6/2005 02:34:42 PM, Kind = Utc
'  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
'  ToUniversalTime: 5/6/2005 02:34:42 PM, Kind = Utc
'
'Local: ........... 5/6/2005 02:34:42 PM, Kind = Local
'  ToLocalTime:     5/6/2005 02:34:42 PM, Kind = Local
'  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc
'
'Unspecified: ..... 5/6/2005 02:34:42 PM, Kind = Unspecified
'  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
'  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc
'

注解

协调世界时(UTC)等于本地时间减去 UTC 偏移量。The Coordinated Universal Time (UTC) is equal to the local time minus the UTC offset. 有关 UTC 偏移量的详细信息,请参阅 TimeZone.GetUtcOffsetFor more information about the UTC offset, see TimeZone.GetUtcOffset. 该转换还会考虑适用于当前 @no__t 0 对象所表示的时间的夏令时规则。The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.

重要

Windows XPWindows XP 系统上,第 1 @no__t 方法仅在从本地时间转换为 UTC 时识别当前调整规则。On Windows XPWindows XP systems, the ToUniversalTime method recognizes only the current adjustment rule when converting from local time to UTC. 因此,当前调整规则生效前的时间转换可能无法准确反映本地时间和 UTC 之间的时差。As a result, conversions for periods before the current adjustment rule came into effect may not accurately reflect the difference between local time and UTC.

从 .NET Framework 版本2.0 开始,ToUniversalTime 方法返回的值由当前 @no__t 2 对象的 Kind 属性确定。Starting with the .NET Framework version 2.0, the value returned by the ToUniversalTime method is determined by the Kind property of the current DateTime object. 下表描述了可能的结果。The following table describes the possible results.

类型Kind 结果Results
Utc 不执行任何转换。No conversion is performed.
Local 当前 @no__t 为-0 的对象将转换为 UTC。The current DateTime object is converted to UTC.
Unspecified 当前 @no__t 0 对象被假定为本地时间,执行转换的方式与 Kind Local 一样。The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local.

备注

@No__t-0 方法将 @no__t 的值从本地时间转换为 UTC。The ToUniversalTime method converts a DateTime value from local time to UTC. 若要将非本地时区中的时间转换为 UTC,请使用 TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) 方法。To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. 若要转换与 UTC 的偏移量已知的时间,请使用 ToUniversalTime 方法。To convert a time whose offset from UTC is known, use the ToUniversalTime method.

如果日期和时间实例值是不明确的时间,则此方法假定它是标准时间。If the date and time instance value is an ambiguous time, this method assumes that it is a standard time. (不明确的时间是指可以映射到标准时间或本地时区的夏令时的时间)如果日期和时间实例的值无效,则此方法只需将本地时区的 UTC 偏移量减去本地时间即可返回 UTC。(An ambiguous time is one that can map either to a standard time or to a daylight saving time in the local time zone) If the date and time instance value is an invalid time, this method simply subtracts the local time from the local time zone's UTC offset to return UTC. (无效时间是由于应用夏令时调整规则而不存在的时间。)(An invalid time is one that does not exist because of the application of daylight saving time adjustment rules.)

调用方说明

@No__t-0 方法有时用于将本地时间转换为 UTC。The ToUniversalTime() method is sometimes used to convert a local time to UTC. 然后调用 ToLocalTime() 方法来还原原始的本地时间。The ToLocalTime() method is then called to restore the original local time. 但是,如果原始时间表示本地时区中的无效时间,则两个本地时间值将不相等。However, if the original time represents an invalid time in the local time zone, the two local time values will not be equal. 有关其他信息和示例,请参阅 ToLocalTime() 方法。For additional information and an example, see the ToLocalTime() method.

Windows XPWindows XP 系统上,第 1 @no__t 方法仅识别本地时区的当前调整规则,该规则应用于所有日期,包括下级日期(即早于当前调整规则开始日期的日期)。On Windows XPWindows XP systems, the ToUniversalTime() method recognizes only the current adjustment rule for the local time zone, which it applies to all dates, including down-level dates (that is, dates that are earlier than the starting date of the current adjustment rule). 在 @no__t 上运行的应用程序需要过时的本地日期和时间计算,则必须通过使用 FindSystemTimeZoneById(String) 方法检索与本地时区对应的 TimeZoneInfo 对象并调用其 ConvertTimeToUtc(DateTime, TimeZoneInfo) 方法,来解决此行为。Applications running on Windows XPWindows XP that require historically accurate local date and time calculations must work around this behavior by using the FindSystemTimeZoneById(String) method to retrieve a TimeZoneInfo object that corresponds to the local time zone and calling its ConvertTimeToUtc(DateTime, TimeZoneInfo) method.

下面的示例说明了美国英语的 Windows XPWindows XP 系统上的 @no__t 0 和 @no__t 方法之间的差异。The following example illustrates the difference between the ToUniversalTime() and ConvertTimeToUtc(DateTime, TimeZoneInfo) methods on a Windows XPWindows XP system in the U.S. Pacific Time zone. 前两种方法调用将当前时区调整规则(在2007中生效)应用于2006中的日期。The first two method calls apply the current time zone adjustment rule (which went into effect in 2007) to a date in 2006. 当前调整规则用于在三月的第二个星期日转换到夏令时以前的规则(在2006中有效)在4月的第一个星期日开始转换为夏令时。The current adjustment rule provides for the transition to daylight saving time on the second Sunday of March; the previous rule, which was in effect in 2006, provided for the transition to daylight saving time to occur on the first Sunday of April. 只有第三个方法调用才能准确地执行此历史日期和时间转换。Only the third method call accurately performs this historical date and time conversion.

[!code-csharpSystem.DateTime.ToUniversalTime#1] [!code-vbSystem.DateTime.ToUniversalTime#1][!code-csharpSystem.DateTime.ToUniversalTime#1] [!code-vbSystem.DateTime.ToUniversalTime#1]

适用于

另请参阅