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


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


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

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

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


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

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

示例1:

// C# program to demonstrate the 
// DateTimeOffset.AddHours(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 hours to the value of this  
            // instance using AddHours() method 
            DateTimeOffset value = offset.AddHours(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/01/2007 17:55:00 -05:00

示例2:對於ArgumentOutOfRangeException

// C# program to demonstrate the 
// DateTimeOffset.AddHours(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 AddHours(Double) method; 
            DateTimeOffset value = offset.AddHours(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.AddHours() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。