Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức DateTime.Subtract() trong C#

Phương thức DateTime.Subtract() trong C# trừ đi DateTime hoặc TimeSpan được chỉ định.

Cú pháp

public TimeSpan Subtract(DateTime value);
public DateTime Subtract(TimeSpan value);

Ví dụ 1: Trừ hai DateTime

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);
    }
}

Đầu ra

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

Ví dụ 2: Trừ TimeSpan từ DateTime

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);
    }
}

Đầu ra

Date = 10/10/2019 8:10:40 AM
DateTime between date d and timespan t = 10/8/2019 10:00:28 PM