當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# DateTimeOffset.FromUnixTimeSeconds()用法及代碼示例


DateTimeOffset.FromUnixTimeSeconds(Int64)方法用於將表示從1970-01-01T00:00:00Z開始經過的秒數的Unix時間轉換為DateTimeOffset值。

用法: public static DateTimeOffset FromUnixTimeSeconds (long seconds);
Here, it takes a Unix time, expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC). For Unix times before this date, its value is negative.

返回值:此方法返回的日期和時間值表示與Unix時間相同的時刻。


異常:如果秒數小於-62,135,596,800或秒數大於253,402,300,799,則此方法將提供ArgumentOutOfRangeException。

以下示例程序旨在說明DateTimeOffset.FromUnixTimeSeconds(Int64)方法的用法:

示例1:

// C# program to demonstrate the 
// DateTimeOffset.FromUnixTimeSeconds(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 seconds 
            // that have elapsed since  
            // 1970-01-01T00:00:00Z to a  
            // DateTimeOffset value instance  
            // using FromUnixTimeSeconds() method 
            DateTimeOffset value =  
               DateTimeOffset.FromUnixTimeSeconds(10000); 
  
            // 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 02:46:40 +00:00

示例2:對於ArgumentOutOfRangeException

// C# program to demonstrate the 
// DateTimeOffset.FromUnixTimeSeconds(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 seconds 
            // that have elapsed since  
            // 1970-01-01T00:00:00Z to a  
            // DateTimeOffset value instance  
            // using FromUnixTimeSeconds() method 
            DateTimeOffset value =  
              DateTimeOffset.FromUnixTimeSeconds(254402300799); 
  
            // 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

參考:



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 DateTimeOffset.FromUnixTimeSeconds() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。