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


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


此方法用於返回一個新的DateTimeOffset對象,該對象將一個指定的時間間隔添加到此實例的值。

用法: public DateTimeOffset Add (TimeSpan timeSpan);
Here, it takes a TimeSpan object that represents a positive or a negative time interval.

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


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

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

示例1:

// C# program to demonstrate the 
// DateTimeOffset.Add(TimeSpan) 
// 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)); 
                                                         
  
            // creating object of TimeSpan 
            TimeSpan elapsedTime = new TimeSpan(10, 0, 0); 
  
            // adding a specified time interval  
            // to the value of this instance. 
            // using Add() method; 
            DateTimeOffset value = offset.Add(elapsedTime); 
  
            // 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/01/2007 17:55:00 -05:00

示例2:對於ArgumentOutOfRangeException

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