C# 中的 DateTime.Subtract() 方法
C# 中的 DateTime.Subtract() 方法用于减去指定的 DateTime 或跨度。
语法
以下是语法 −
public TimeSpan Subtract (DateTime value); public DateTime Subtract (TimeSpan value);
示例
现在让我们看一个示例来实现 DateTime.Subtract() 方法 −
using System; public class Demo { public static void Main() { DateTime d1 = new DateTime(2019, 10, 10, 8, 10, 40); DateTime d2 = new DateTime(2017, 11, 06, 8, 10, 40); Console.WriteLine("Date 1 = "+d1); Console.WriteLine("Date 2 = "+d2); TimeSpan res = d1.Subtract(d2); Console.WriteLine("TimeSpan between two dates = {0} ",res); } }
输出
将产生以下输出 −
Date 1 = 10/10/2019 8:10:40 AM Date 2 = 11/6/2017 8:10:40 AM TimeSpan between two dates = 703.00:00:00
示例
现在让我们看另一个示例来实现 DateTime.Subtract() 方法 −
using System; public class Demo { public static void Main() { DateTime d = new DateTime(2019, 10, 10, 8, 10, 40); TimeSpan t = new TimeSpan(1, 10, 10, 12); Console.WriteLine("Date = "+d); DateTime res = d.Subtract(t); Console.WriteLine("DateTime between date d and timespan t = {0} ",res); } }
输出
将产生以下输出 −
Date = 10/10/2019 8:10:40 AM DateTime between date d and timespan t = 10/8/2019 10:00:28 PM
广告