job 1393 job 1393 - 1 month ago 19
C# Question

How to get Difference hours Between two date

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;


When I want get Hours its return mines (-11 e.t).

How can I get positive Diffrence Hour ?

anyone can you help me?
I want get Last Dat and show its by string how days afterd now.

Answer

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 TotalDays, TotalHours and TotalMinutes.

If you always want a positive TimeSpan - the equivalent of Math.Abs but for TimeSpan you can just use TimeSpan.Duration():

TimeSpan difference = (DateTime.Now - lastDate).Duration();
Comments