C# - Difference between two dates?
11,785
Solution 1
int days = (int)Math.Ceiling(diff.TotalDays);
Solution 2
The question is rather philosophic; if Christmas was tomorrow, would you consider it to be 1 day left, or 0 days left. If you put the day of tomorrow into your calculation, the answer will be 0.
Solution 3
Your problem goes away if you replace your:
DateTime.Now
with:
DateTime.Today
as your difference calculation will then be working in whole days.
Author by
user
Updated on June 04, 2022Comments
-
user almost 2 years
I am trying to calculate the difference between two dates. This is what I'm currently using:
int currentyear = DateTime.Now.Year; DateTime now = DateTime.Now; DateTime then = new DateTime(currentyear, 12, 26); TimeSpan diff = now - then; int days = diff.Days; label1.Text = days.ToString() + " Days Until Christmas";
All works fine except it is a day off. I am assuming this is because it does not count anything less than 24 hours a complete day. Is there a way to get it to do so? Thank you.
-
Rubens Farias over 14 yearsCannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
-
user over 14 yearsint days = Convert.ToInt32(Math.Ceiling(diff.TotalDays));
-
LorenVS over 14 yearsOops, assumed Math.Ceiling returned int... kind of stupid now that I think about it
-
user over 14 yearsAny idea why it's returning a "-" before the number of days?
-
user over 14 yearsOh wow, I feel dumb. Well I changed that and then it was returning the wrong value for the days, so I ended up using the int days = diff.Days; as I originally did.