I want get diffrences Day,Hour and Day between two days.
I use belowe Code :
DateTime LastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
int differenceDay = DateTime.Now.Subtract(LastDate).Days;
int differenceHoure = DateTime.Now.Hour - LastDate.Hour;//returns -11
int differenceMinute = DateTime.Now.Minute - LastDate.Minute;
You're subtracting component-wise (i.e. "this hour-of-day minus that hour-of-day, this minute-of-hour minus that minute-of-hour"). Don't do that - it won't work if the current hour-of-day is earlier than the hour-of-day of
lastDate, or the same for minute-of-hour - you get a negative value, exactly as you've seen.
Instead, subtract one
DateTime from another to get a
TimeSpan and use that single
TimeSpan for all the components:
DateTime lastDate = DateTime.Parse("2/12/2015 11:24:23 AM"); TimeSpan difference = DateTime.Now - lastDate; int days = difference.Days; int hours = difference.Hours; int minutes = difference.Minutes;
That will still be negative if
lastDate is after
DateTime.Now, of course.
Note that this will give you a result which is meaningful if you display all three components. For example, it might give you "2 days, 3 hours and 10 minutes". If instead you want to represent the same
TimeSpan as "2.194 days" or "51.166 hours" or "3160 minutes" then you can use
If you always want a positive
TimeSpan - the equivalent of
Math.Abs but for
TimeSpan you can just use
TimeSpan difference = (DateTime.Now - lastDate).Duration();