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


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


此方法用於返回一個新的DateTimeOffset對象,該對象將指定天數的整數和小數天加到該實例的值上。

用法: public DateTimeOffset AddDays (double days);
Here, it takes a number of whole and fractional days.

返回值:此方法返回一個對象,該對象的值是當前DateTimeOffset對象表示的日期和時間與天數表示的天數之和。


異常:如果結果DateTimeOffset的值小於MinValue或結果DateTimeOffset的值大於MaxValue,則此方法將提供ArgumentOutOfRangeException。

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

示例1:

// C# program to demonstrate the 
// DateTimeOffset.AddDays(Double) 
// Method 
using System; 
using System.Globalization; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // creating object of  DateTimeOffset 
            DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, 
                                                     new TimeSpan(-5, 0, 0)); 
  
            // adding a specified number of whole  
            // and fractional days to the value  
            // of this instance using AddDays(Double)  
            // method 
            DateTimeOffset value = offset.AddDays(10); 
  
            // 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 06/11/2007 07:55:00 -05:00

示例2:對於ArgumentOutOfRangeException

// C# program to demonstrate the 
// DateTimeOffset.AddDays(Double) 
// Method 
using System; 
using System.Globalization; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        try { 
  
            // creating object of  DateTimeOffset 
            DateTimeOffset offset = DateTimeOffset.MaxValue; 
  
            // adding a specified number of whole and 
            // fractional days to the value of this instance. 
            // using AddDays(Double) method; 
            DateTimeOffset value = offset.AddDays(10); 
  
            // 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.AddDays() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。