DateTime difference in days on the basis of Date only

后端 未结 3 1345
深忆病人
深忆病人 2020-12-28 15:14

I need to find the difference in days between two dates.

For example:

Input: **startDate** = 12-31-2012 23hr:59mn:00sec, **endDate** = 01-01-2013 00hr:

相关标签:
3条回答
  • 2020-12-28 15:18

    If you use the DateTime.Date property this will eliminate the time

    date1.Date.Subtract(date2.Date).Days
    
    0 讨论(0)
  • 2020-12-28 15:19

    Well, it sounds like you want the difference in the number of days, ignoring the time component. A DateTime with the time component reset to 00:00:00 is what the Date property gives you:

    (startDate.Date - endDate.Date).TotalDays
    
    0 讨论(0)
  • 2020-12-28 15:20

    Use TimeStamp. Just subtract two dates (using DateTime.Date property), get the difference in time span and return TotalDays

    TimeSpan ts = endDate.Date - startDate.Date;
    double TotalDays = ts.TotalDays;
    

    So your extension method can be as simple as:

    public static int GetDifferenceInDaysX(this DateTime startDate, DateTime endDate)
        {
          return (int) (endDate.Date - startDate.Date).TotalDays;
          // to return just a int part of the Total days, you may round it according to your requirement
        }
    

    EDIT: Since the question has been edited, you may check the following example. Consider the following two dates.

    DateTime startDate = new DateTime(2012, 12, 31, 23, 59, 00);
    DateTime endDate = new DateTime(2013, 01, 01, 00, 15, 00); 
    

    You can write the extension method as:

    public static int GetDifferenceInDaysX(this DateTime startDate, DateTime endDate)
        {
            TimeSpan ts = endDate - startDate;
            int totalDays = (int) Math.Ceiling(ts.TotalDays);
            if (ts.TotalDays < 1 && ts.TotalDays > 0)
                totalDays = 1;
            else
                totalDays = (int) (ts.TotalDays);
            return totalDays;
        }
    

    For the above dates it will give you 1

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