Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Difference between two dates?

Tags:

date

c#

timespan

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.

like image 263
user Avatar asked Dec 03 '09 10:12

user


3 Answers

int days = (int)Math.Ceiling(diff.TotalDays);
like image 144
LorenVS Avatar answered Sep 20 '22 21:09

LorenVS


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.

like image 32
Espen Medbø Avatar answered Sep 19 '22 21:09

Espen Medbø


Your problem goes away if you replace your:

DateTime.Now

with:

DateTime.Today

as your difference calculation will then be working in whole days.

like image 35
stovroz Avatar answered Sep 18 '22 21:09

stovroz