DateTime.ToLocalTime DateTime.ToLocalTime DateTime.ToLocalTime DateTime.ToLocalTime Method

Definición

Convierte el valor del objeto DateTime actual a la hora local.Converts the value of the current DateTime object to local time.

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

Devoluciones

Objeto cuya propiedad Kind es Local, y cuyo valor es la hora local 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 Local, and whose value is the local time 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 as a DateTime object.

Ejemplos

En el ejemplo siguiente se muestra el ToLocalTime método.The following example demonstrates the ToLocalTime method. Tenga en cuenta que el resultado exacto depende de la referencia cultural actual y la zona horaria local del sistema en el que se ejecuta.Note that the exact output depends on the current culture and the local time zone of the system on which it is run.

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 SpecifyKind método para demostrar cómo el Kind influye en la propiedad la ToLocalTime y ToUniversalTime métodos de conversión.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.
Imports System

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 'Main
    
    ' 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
    
    
    ' 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 'DisplayNow
End Class 'Sample

'
'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 local es igual a la hora de la hora Universal coordinada (UTC) más el desplazamiento de UTC.The local time is equal to the Coordinated Universal Time (UTC) time plus the UTC offset. Para obtener más información sobre la diferencia horaria con UTC, consulte 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 actual DateTime objeto.The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.

Importante

En Windows XPWindows XP sistemas, la ToLocalTime método reconoce solo la regla de ajuste actual al convertir la hora UTC a la hora local.On Windows XPWindows XP systems, the ToLocalTime method recognizes only the current adjustment rule when converting from UTC to local time. Como resultado, puede que las conversiones para períodos antes de la regla de ajuste actual entró en efecto no reflejan con precisión la diferencia entre la hora UTC y la hora local.As a result, conversions for periods before the current adjustment rule came into effect may not accurately reflect the difference between UTC and local time.

A partir de .NET Framework versión 2.0, el valor devuelto por la ToLocalTime método viene determinada por la Kind propiedad del elemento actual DateTime objeto.Starting with the .NET Framework version 2.0, the value returned by the ToLocalTime method is determined by the Kind property of the current DateTime object. En la tabla siguiente se describe los posibles resultados.The following table describes the possible results.

KindKind ResultadosResults
Utc Esta instancia de DateTime se convierte en hora local.This instance of DateTime is converted to local time.
Local Se realiza ninguna conversión.No conversion is performed.
Unspecified Esta instancia de DateTime se supone que es una hora UTC, y la conversión se realiza como si Kind eran Utc.This instance of DateTime is assumed to be a UTC time, and the conversion is performed as if Kind were Utc.

Nota

El ToLocalTime método convierte un DateTime valor a la hora UTC a la hora local.The ToLocalTime method converts a DateTime value from UTC to local time. Para convertir la hora de cualquier zona horaria designada a la hora local, use el TimeZoneInfo.ConvertTime método.To convert the time in any designated time zone to local time, use the TimeZoneInfo.ConvertTime method.

El valor devuelto por la conversión es un DateTime cuyo Kind propiedad siempre devuelve Local.The value returned by the conversion is a DateTime whose Kind property always returns Local. Por lo tanto, se devuelve un resultado válido aunque ToLocalTime se aplica repetidamente a la misma DateTime.Consequently, a valid result is returned even if ToLocalTime is applied repeatedly to the same DateTime.

Notas a los autores de las llamadas

Puede usar el ToLocalTime() método para restaurar una fecha local y el valor de tiempo que se convirtió a UTC mediante el ToUniversalTime() o FromFileTimeUtc(Int64) método.You can use the ToLocalTime() method to restore a local date and time value that was converted to UTC by the ToUniversalTime() or FromFileTimeUtc(Int64) method. Sin embargo, si la hora original representa una hora no válida en la zona horaria local, no coincidirá el valor restaurado.However, if the original time represents an invalid time in the local time zone, it will not match the restored value. Cuando el ToLocalTime() método convierte una hora a la hora UTC a la zona horaria local, también ajusta la hora para que sea válida en la zona horaria local.When the ToLocalTime() method converts a time from UTC to the local time zone, it also adjusts the time so that is valid in the local time zone.

Por ejemplo, se produce la transición desde el horario estándar al horario de verano en Estados Unidos Zona horaria del Pacífico de 14 de marzo de 2010, a las 2:00 A.M., cuando la hora se adelanta una hora, a las 3:00 A.M.For example, the transition from standard time to daylight saving time occurs in the U.S. Pacific Time zone on March 14, 2010, at 2:00 A.M., when the time advances by one hour, to 3:00 A.M. Este intervalo de hora es una hora no válida, es decir, un intervalo de tiempo que no existe en esta zona horaria.This hour interval is an invalid time, that is, a time interval that does not exist in this time zone. El ejemplo siguiente se muestra que cuando una hora que se encuentra dentro de este intervalo se convierte a UTC mediante el ToUniversalTime() método y, a continuación, se restaura por la ToLocalTime() método, el valor original se ajusta para ser una hora válida.The following example shows that when a time that falls within this range is converted to UTC by the ToUniversalTime() method and is then restored by the ToLocalTime() method, the original value is adjusted to become a valid time. Puede determinar si una fecha determinada y el valor de tiempo pueden estar sujeto a modificación pasándolo a la IsInvalidTime(DateTime) método, como en el ejemplo se muestra.You can determine whether a particular date and time value may be subject to modification by passing it to the IsInvalidTime(DateTime) method, as the example illustrates.

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

Se aplica a

Consulte también: