Subtracting two dates

前端 未结 3 1096
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 03:05

I have two calendars and each return a DateTime from calendar.SelectedDate.

How do I go about subtracting the two selected dates from each other, giving me the amoun

相关标签:
3条回答
  • 2020-12-29 03:38

    Think about it.
    How do you express a difference betwen two dates? With another date?
    That's why you need the TimeSpan

    DateTime dtToday = new System.DateTime(2012, 6, 2, 0, 0, 0);
    DateTime dtMonthBefore = new System.DateTime(2012, 5, 2, 0, 0, 0);
    TimeSpan diffResult = dtToday.Subtract(dtMonthBefore);
    Console.WriteLine(diffResult.TotalDays);
    
    0 讨论(0)
  • 2020-12-29 03:42

    You can use someDateTime.Subtract(otherDateTime), this returns a TimeSpan which has a TotalDays property.

    0 讨论(0)
  • 2020-12-29 03:53

    Just use:

    TimeSpan difference = end - start;
    double days = difference.TotalDays;
    

    Note that if you want to treat them as dates you should probably use

    TimeSpan difference = end.Date - start.Date;
    int days = (int) difference.TotalDays;
    

    That way you won't get different results depending on the times.

    (You can use the Subtract method instead of the - operator if you want, but personally I find it clearer to use the operator.)

    0 讨论(0)
提交回复
热议问题