Calculate difference between two dates returns a negative number

前端 未结 4 1166
予麋鹿
予麋鹿 2021-01-15 05:12

I am trying to calculate how many days there are between different dates. Like the topic says, I\'m getting a negative value. I guess I could just take the absolute value, b

4条回答
  •  旧巷少年郎
    2021-01-15 05:50

    Ofcourse 3-31 gives -28, but since we want it to show days between, it makes no sense that it doesn't return a positive value. Am I doing something wrong?

    I think that you don't know which date is greater before hand.And your naming is just confusing.

    You can first check which date is greater and then subtract the Lesser from the greater

    TimeSpan differenceInDays;
    double xAxisValue;
    if(nextDay > previousDay )
    {
        differenceInDays = (nextDay - previousDay); 
    }
    else
    {
        differenceInDays = (previousDay - nextDay); 
    }
    xAxisValue = differenceInDays.TotalDays;
    

提交回复
热议问题