DateTime.ToLocalTime Methode

Definition

Konvertiert den Wert des aktuellen DateTime-Objekts in die Ortszeit.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

Gibt zurück

Ein Objekt, dessen Kind-Eigenschaft Local ist und dessen Wert die Ortszeit ist, die dem Wert des aktuellen DateTime-Objekts entspricht, oder MaxValue, wenn der konvertierte Wert zu groß ist, um von einem DateTime-Objekt dargestellt zu werden, oder MinValue, wenn der konvertierte Wert zu klein ist, um als DateTime-Objekt dargestellt zu werden.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.

Beispiele

Das folgende Beispiel veranschaulicht die ToLocalTime Methode.The following example demonstrates the ToLocalTime method. Beachten Sie, dass die genaue Ausgabe von der aktuellen Kultur und der lokalen Zeitzone des Systems abhängt, in dem Sie ausgeführt wird.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.

Im folgenden Beispiel wird die SpecifyKind-Methode verwendet, um zu veranschaulichen, wie die Kind-Eigenschaft die Konvertierungs Methoden ToLocalTime und ToUniversalTime beeinflusst.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
'

Hinweise

Die Ortszeit ist gleich der UTC-Zeit (koordinierte Weltzeit) plus dem UTC-Offset.The local time is equal to the Coordinated Universal Time (UTC) time plus the UTC offset. Weitere Informationen zum UTC-Offset finden Sie unter TimeZone.GetUtcOffset.For more information about the UTC offset, see TimeZone.GetUtcOffset. Die Konvertierung berücksichtigt auch die Sommerzeit Regel, die sich auf die Zeit bezieht, die durch das aktuelle DateTime-Objekt dargestellt wird.The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.

Wichtig

Auf Windows XPWindows XP-Systemen erkennt die ToLocalTime-Methode nur die aktuelle Anpassungs Regel, wenn Sie von UTC in lokale Zeit umschließt.On Windows XPWindows XP systems, the ToLocalTime method recognizes only the current adjustment rule when converting from UTC to local time. Daher wird der Unterschied zwischen UTC und Ortszeit durch Konvertierungen für Zeiträume vor der aktuellen Anpassungs Regel möglicherweise nicht genau widerspiegelt.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.

Beginnend mit der .NET Framework Version 2,0 wird der Wert, der von der ToLocalTime-Methode zurückgegeben wird, von der Kind-Eigenschaft des aktuellen DateTime-Objekts bestimmt.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. In der folgenden Tabelle werden die möglichen Ergebnisse beschrieben.The following table describes the possible results.

ArtKind ErgebnisseResults
Utc Diese Instanz von DateTime wird in die lokale Zeit konvertiert.This instance of DateTime is converted to local time.
Local Es wird keine Konvertierung durchgeführt.No conversion is performed.
Unspecified Diese Instanz von DateTime wird als UTC-Zeit angenommen, und die Konvertierung erfolgt wie bei Kind Utc.This instance of DateTime is assumed to be a UTC time, and the conversion is performed as if Kind were Utc.

Hinweis

Die ToLocalTime-Methode konvertiert einen DateTime-Wert von der UTC in die lokale Zeit.The ToLocalTime method converts a DateTime value from UTC to local time. Verwenden Sie die TimeZoneInfo.ConvertTime-Methode, um die Zeit in einer bestimmten Zeitzone in eine lokale Zeit zu konvertieren.To convert the time in any designated time zone to local time, use the TimeZoneInfo.ConvertTime method.

Der von der Konvertierung zurückgegebene Wert ist ein DateTime, dessen Kind-Eigenschaft immer Local zurückgibt.The value returned by the conversion is a DateTime whose Kind property always returns Local. Folglich wird ein gültiges Ergebnis zurückgegeben, auch wenn ToLocalTime wiederholt auf denselben DateTime angewendet wird.Consequently, a valid result is returned even if ToLocalTime is applied repeatedly to the same DateTime.

Hinweise für Aufrufer

Sie können die ToLocalTime()-Methode verwenden, um einen lokalen Datums-und Uhrzeitwert wiederherzustellen, der durch die ToUniversalTime()-oder FromFileTimeUtc(Int64)-Methode in die UTC konvertiert wurde.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. Wenn die ursprüngliche Zeit jedoch eine ungültige Zeit in der lokalen Zeitzone darstellt, entspricht Sie nicht dem wiederhergestellten Wert.However, if the original time represents an invalid time in the local time zone, it will not match the restored value. Wenn die ToLocalTime()-Methode eine Uhrzeit von der UTC in die lokale Zeitzone konvertiert, wird auch die Uhrzeit angepasst, sodass Sie in der lokalen Zeitzone gültig ist.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.

Die Umstellung von Standardzeit auf Sommerzeit erfolgt beispielsweise in den USA Pacific Time Zone am 14. März 2010 um 2:00 Uhr, wenn die Zeit um eine Stunde um um 3:00 Uhr liegtFor 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. Dieses Stunden Intervall ist eine ungültige Zeit, d. h. ein Zeitintervall, das in dieser Zeitzone nicht vorhanden ist.This hour interval is an invalid time, that is, a time interval that does not exist in this time zone. Das folgende Beispiel zeigt, dass eine Zeitspanne, die in diesen Bereich fällt, von der ToUniversalTime()-Methode in UTC konvertiert und dann mit der ToLocalTime()-Methode wieder hergestellt wird. der ursprüngliche Wert wird so angepasst, dass er ein gültiger Zeitpunkt ist.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. Sie können feststellen, ob ein bestimmter Datums-und Uhrzeitwert geändert werden kann, indem Sie ihn an die IsInvalidTime(DateTime)-Methode übergeben, wie im Beispiel veranschaulicht.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]

Gilt für:

Siehe auch