📜  C#中的DateTime.SpecifyKind()方法

📅  最后修改于: 2021-05-30 00:03:39             🧑  作者: Mango

此方法用于创建一个新的DateTime对象,该对象的跳动次数与指定的DateTime相同,但被指定为本地时间,协调世界时(UTC)或都不指定,如指定的DateTimeKind值所示。

下面的程序说明了DateTime.SpecifyKind(DateTime,DateTimeKind)方法的用法:

范例1:

// C# program to demonstrate the
// DateTime.SpecifyKind(DateTime,
// DateTimeKind) Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating object of DateTime
        DateTime date = new DateTime(2005, 5,
                                6, 14, 34, 42);
                                  
        Console.WriteLine("Kind Before Using Method: "
                                          +date.Kind);
  
        // getting DateTime of same DateTime 
        // instance using SpecifyKind() method
        DateTime value = DateTime.SpecifyKind(date,
                            DateTimeKind.Local);
                              
        Console.WriteLine("Kind After Using Method: " +
                                            value.Kind);
  
        Console.WriteLine("DateTime is {0}",
                                    value);
    }
}
输出:
Kind Before Using Method: Unspecified
Kind After Using Method: Local
DateTime is 05/06/2005 14:34:42

范例2:

// C# program to demonstrate the
// DateTime.SpecifyKind(DateTime,
// DateTimeKind) Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating object of DateTime
        DateTime date = new DateTime(1970, 1,
                                1, 4, 0, 15);
  
        // getting DateTime of same DateTime 
        // instance using SpecifyKind() method
        DateTime value = DateTime.SpecifyKind(date,
                               DateTimeKind.Local);
  
        Console.WriteLine("DateTime is {0}", value);
    }
}
输出:
DateTime is 01/01/1970 04:00:15

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime.specifykind?view=netframework-4.7.2