DateTime.ToLocalTime 方法

定义

将当前 DateTime 对象的值转换为本地时间。

C#
public DateTime ToLocalTime();

返回

Kind属性为 Local的对象,其值为等效于当前DateTime对象的值的本地时间;如果转换的值太大而无法由 DateTime 对象表示,则为 DateTime.MaxValue;如果转换的值太小而无法表示为DateTime对象,则为 DateTime.MinValue

示例

下面的示例演示 ToLocalTime 方法。 请注意,确切的输出取决于运行它的系统的当前区域性和本地时区。

C#
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.

以下示例使用 SpecifyKind 方法演示 属性如何影响 KindToLocalTimeToUniversalTime 转换方法。

C#
// 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

*/

注解

本地时间等于协调世界时 (UTC) 时间加上 UTC 偏移量。 有关 UTC 偏移量的详细信息,请参阅 TimeZoneInfo.GetUtcOffset。 转换还考虑了应用于当前 DateTime 对象所表示时间的夏令时规则。

重要

在 Windows XP 系统上,方法 ToLocalTime 在从 UTC 转换为本地时间时仅识别当前调整规则。 因此,在当前调整规则生效之前的时间段的转换可能无法准确反映 UTC 和本地时间之间的差异。

从 .NET Framework 版本 2.0 开始,方法返回ToLocalTime的值由Kind当前 DateTime 对象的 属性确定。 下表描述了可能的结果。

种类 结果
Utc 的此实例 DateTime 将转换为本地时间。
Local 不执行任何转换。
Unspecified 的此实例DateTime假定为 UTC 时间,并且转换将像 一样KindUtc执行。

备注

方法 ToLocalTimeDateTime 值从 UTC 转换为本地时间。 若要将任何指定时区中的时间转换为本地时间,请使用 TimeZoneInfo.ConvertTime 方法。

转换返回的值是 , DateTimeKind 属性始终返回 Local。 因此,即使 ToLocalTime 重复应用于同 DateTime一个 ,也会返回有效的结果。

调用方说明

可以使用 ToLocalTime() 方法还原通过 ToUniversalTime()FromFileTimeUtc(Int64) 方法转换为 UTC 的本地日期和时间值。 但是,如果原始时间表示本地时区中的无效时间,则它与还原的值不匹配。 ToLocalTime()当 方法将时间从 UTC 转换为本地时区时,它还会调整时间,使其在本地时区中有效。

例如,从标准时间到夏令时制的转换发生在美国太平洋时区 2010 年 3 月 14 日凌晨 2:00,时间提前一小时到凌晨 3:00。此小时间隔是无效时间,即此时区中不存在的时间间隔。 以下示例显示,当属于此范围内的时间由 ToUniversalTime() 方法转换为 UTC,然后由 ToLocalTime() 方法还原时,原始值将调整为有效时间。 如示例所示,可以通过将特定日期和时间值传递给 IsInvalidTime(DateTime) 方法来确定特定日期和时间值是否可进行修改。

C#
using System;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 0, DateTimeKind.Local);
      Console.WriteLine("Invalid time: {0}",
                        TimeZoneInfo.Local.IsInvalidTime(date1));
      DateTime utcDate1 = date1.ToUniversalTime();
      DateTime date2 = utcDate1.ToLocalTime();
      Console.WriteLine("{0} --> {1}", date1, date2);
   }
}
// The example displays the following output:
//       Invalid time: True
//       3/14/2010 2:30:00 AM --> 3/14/2010 3:30:00 AM

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅