此方法用於返回新的DateTime,該日期將指定的滴答數添加到此實例的值。此方法不會更改此DateTime的值。而是返回一個新的DateTime,其值是此操作的結果。
用法:
public DateTime AddTicks (long value);
在這裏,它需要100納秒的刻度。
返回值:此方法返回一個對象,其值是此實例表示的日期和時間與value表示的時間之和。
異常:如果生成的DateTime小於MinValue或大於MaxValue,則此方法將提供ArgumentOutOfRangeException。
以下示例程序旨在說明DateTime.AddTicks(Int64)方法的用法:
示例1:
// C# program to demonstrate the
// DateTime.AddTicks(Double) Method
using System;
class GFG {
// Main Method
public static void Main()
{
try {
// creating object of DateTime
DateTime date1 = new DateTime(2010, 1,
1, 4, 0, 15);
// adding the 3000 ticks
// using AddTicks() method;
DateTime date2 = date1.AddTicks(3000);
// Display the date1
Console.WriteLine("No. of ticks before operation: "
+ "{0}", date1.Ticks);
// Display the date2
Console.WriteLine("\nNo. of ticks after operation: "
+ "{0}", date2.Ticks);
}
catch (ArgumentOutOfRangeException e)
{
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
輸出:
No. of ticks before operation: 633979152150000000 No. of ticks after operation: 633979152150003000
示例2:對於ArgumentOutOfRangeException
// C# program to demonstrate the
// DateTime.AddTicks(long) Method
using System;
class GFG {
// Main Method
public static void Main()
{
try {
// creating object of DateTime
// and initialize with MinValue
DateTime date1 = DateTime.MaxValue;
// Display the date1
Console.WriteLine("DateTime before operation: "
+ "{0}", date1.Ticks);
// adding the 1 Ticks
// using AddTicks() method;
DateTime date2 = date1.AddTicks(1);
// Display the date2
Console.WriteLine("\nDateTime after operation: "
+ "{0}", date2.Ticks);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("\nThe resulting DateTime is "+
"greater than the DateTime.MaxValue ");
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
輸出:
DateTime before operation: 3155378975999999999 The resulting DateTime is greater than the DateTime.MaxValue Exception Thrown: System.ArgumentOutOfRangeException
參考:
相關用法
- C# Uri.IsBaseOf(Uri)用法及代碼示例
- C# Random.Next()用法及代碼示例
- C# Uri.ToString()用法及代碼示例
- C# Uri.IsWellFormedOriginalString()用法及代碼示例
- C# Uri.GetHashCode()用法及代碼示例
- C# Math.Log()用法及代碼示例
- C# Uri.FromHex()用法及代碼示例
- C# Uri.IsHexDigit()用法及代碼示例
- C# Queue.Contains()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 DateTime.AddTicks() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。