📜  C#中的DateTimeOffset.FromUnixTimeMilliseconds()方法

📅  最后修改于: 2021-05-29 18:53:00             🧑  作者: Mango

DateTimeOffset.FromUnixTimeMilliseconds(Int64)方法用于将表示从1970-01-01T00:00:00Z开始经过的毫秒数的Unix时间转换为DateTimeOffset值。

下面的程序说明了DateTimeOffset.FromUnixTimeMilliseconds(Int64)方法的用法:

范例1:

// C# program to demonstrate the
// DateTimeOffset.FromUnixTimeMilliseconds(Int64)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Converts a Unix time expressed as 
            // the number of milliseconds that
            // have elapsed since 1970-01-01T00:00:00Z 
            // to a DateTimeOffset value.
            // instance using AddYears() method
            DateTimeOffset value = 
                DateTimeOffset.FromUnixTimeMilliseconds(100000);
  
            // Display the time
            Console.WriteLine("DateTimeOffset is {0}", value);
        }
  
        catch (ArgumentOutOfRangeException e)
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
DateTimeOffset is 01/01/1970 00:01:40 +00:00

示例2:对于ArgumentOutOfRangeException

// C# program to demonstrate the
// DateTimeOffset.FromUnixTimeMilliseconds(Int64)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Converts a Unix time expressed as the
            // number of milliseconds that have elapsed 
            // since 1970-01-01T00:00:00Z to a DateTimeOffset
            // value instance using AddYears() method
            DateTimeOffset value = 
                 DateTimeOffset.FromUnixTimeMilliseconds(253502300799999);
  
            // Display the time
            Console.WriteLine("DateTimeOffset is {0}", value);
        }
  
        catch (ArgumentOutOfRangeException e)
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Exception Thrown: System.ArgumentOutOfRangeException

参考:

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