How to subtract a datetime from another datetime?

后端 未结 7 895
借酒劲吻你
借酒劲吻你 2020-12-03 20:36

How do I subtract two DateTime values from another DateTime value and have the result saved to a double?

相关标签:
7条回答
  • 2020-12-03 21:32
    var Date1 = new DateTime(2018, 12, 15);
    var Date2 = new DateTime(2019, 1, 1);
    TimeSpan result1 = Date2.Subtract(Date1);
    Console.WriteLine(result1);
    
    //To calculate difference between two dates use TotalDays() method
    double result2 = Date2.Subtract(Date1).TotalDays;
    Console.WriteLine(result2);
    
    //Output:
    17.00:00:00
    17
    

    Note:

    • Date2 should be greater than Date1 or else the method will return a negative value
    • Subtract() method returns value of type TimeSpan while TotalDays() method returns value of type double
    0 讨论(0)
提交回复
热议问题