DateTime.ToUniversalTime DateTime.ToUniversalTime DateTime.ToUniversalTime DateTime.ToUniversalTime Method

Definición

Convierte el valor del objeto DateTime actual a la hora universal coordinada (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

Devoluciones

Objeto cuya propiedad Kind es Utc, y cuyo valor es la hora UTC equivalente al valor del objeto DateTime actual, o MaxValue si el valor convertido es demasiado grande para representarlo mediante un objeto DateTime, o MinValue si el valor convertido es demasiado pequeño para representarlo mediante un objeto DateTime.An 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.

Ejemplos

En el ejemplo siguiente se muestra el método 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.

En el ejemplo siguiente se usa el método SpecifyKind para demostrar cómo la propiedad Kind influye en los métodos de conversión @no__t 2 y ToUniversalTime.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
'

Comentarios

La hora universal coordinada (UTC) es igual a la hora local menos el desplazamiento de UTC.The Coordinated Universal Time (UTC) is equal to the local time minus the UTC offset. Para obtener más información sobre el desplazamiento de UTC, vea TimeZone.GetUtcOffset.For more information about the UTC offset, see TimeZone.GetUtcOffset. La conversión también tiene en cuenta la regla de horario de verano que se aplica a la hora representada por el objeto DateTime actual.The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.

Importante

En los sistemas Windows XPWindows XP, el método ToUniversalTime solo reconoce la regla de ajuste actual al convertir de la hora local a la hora UTC.On Windows XPWindows XP systems, the ToUniversalTime method recognizes only the current adjustment rule when converting from local time to UTC. Como resultado, es posible que las conversiones de los períodos anteriores a la regla de ajuste actual surtan efecto, no reflejen con precisión la diferencia entre la hora local y la hora 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.

A partir de la versión 2,0 de .NET Framework, el valor devuelto por el método ToUniversalTime viene determinado por la propiedad Kind del objeto DateTime actual.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. En la tabla siguiente se describen los posibles resultados.The following table describes the possible results.

KindKind ResultadosResults
Utc No se realiza ninguna conversión.No conversion is performed.
Local El objeto DateTime actual se convierte a UTC.The current DateTime object is converted to UTC.
Unspecified Se supone que el objeto DateTime actual es una hora local y la conversión se realiza como si Kind fuera Local.The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local.

Nota

El método ToUniversalTime convierte un valor DateTime de la hora local a UTC.The ToUniversalTime method converts a DateTime value from local time to UTC. Para convertir la hora de una zona horaria no local a UTC, use el método TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo).To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. Para convertir una hora en la que se conoce la diferencia horaria con respecto a la hora UTC, use el método ToUniversalTime.To convert a time whose offset from UTC is known, use the ToUniversalTime method.

Si el valor de la instancia de fecha y hora es una hora ambigua, este método supone que es una hora estándar.If the date and time instance value is an ambiguous time, this method assumes that it is a standard time. (Una hora ambigua es aquella que se puede asignar a una hora estándar o a un horario de verano en la zona horaria local) Si el valor de la instancia de fecha y hora es una hora no válida, este método simplemente resta la hora local del desplazamiento UTC de la zona horaria local para devolver la hora 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. (Una hora no válida es aquella que no existe debido a la aplicación de reglas de ajuste del horario de verano).(An invalid time is one that does not exist because of the application of daylight saving time adjustment rules.)

Notas a los autores de las llamadas

El método ToUniversalTime() a veces se usa para convertir una hora local a UTC.The ToUniversalTime() method is sometimes used to convert a local time to UTC. A continuación, se llama al método ToLocalTime() para restaurar la hora local original.The ToLocalTime() method is then called to restore the original local time. Sin embargo, si la hora original representa una hora no válida en la zona horaria local, los dos valores de hora local no serán iguales.However, if the original time represents an invalid time in the local time zone, the two local time values will not be equal. Para obtener más información y un ejemplo, vea el método ToLocalTime().For additional information and an example, see the ToLocalTime() method.

En los sistemas Windows XPWindows XP, el método ToUniversalTime() solo reconoce la regla de ajuste actual para la zona horaria local, que se aplica a todas las fechas, incluidas las fechas de nivel inferior (es decir, las fechas anteriores a la fecha de inicio de la regla de ajuste actual).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). Las aplicaciones que se ejecutan en Windows XPWindows XP que requieren cálculos de fecha y hora locales históricamente precisos deben solucionar este comportamiento mediante el método FindSystemTimeZoneById(String) para recuperar un objeto @no__t 2 que corresponde a la zona horaria local y llamar a su método 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.

En el ejemplo siguiente se muestra la diferencia entre los métodos ToUniversalTime() y ConvertTimeToUtc(DateTime, TimeZoneInfo) en un sistema @no__t 2 de EE. UU. de EE. UU.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. Las dos primeras llamadas a métodos aplican la regla de ajuste de zona horaria actual (que entró en vigor en 2007) en una fecha en 2006.The first two method calls apply the current time zone adjustment rule (which went into effect in 2007) to a date in 2006. La regla de ajuste actual proporciona la transición al horario de verano en el segundo domingo de marzo; la regla anterior, que estaba en vigor en 2006, se proporcionó la transición al horario de verano en el primer domingo de abril.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. Solo la tercera llamada al método realiza con precisión esta conversión de fecha y hora histórica.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]

Se aplica a

Consulte también: