C# - Difference between two dates?
Asked Answered
S

4

7

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.

Sling answered 3/12, 2009 at 10:25 Comment(0)
T
13
int days = (int)Math.Ceiling(diff.TotalDays);
Tribadism answered 3/12, 2009 at 10:26 Comment(5)
Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)Strophe
int days = Convert.ToInt32(Math.Ceiling(diff.TotalDays));Sling
Oops, assumed Math.Ceiling returned int... kind of stupid now that I think about itTribadism
Any idea why it's returning a "-" before the number of days?Sling
Oh 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.Sling
D
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.

Decretory answered 3/12, 2009 at 10:32 Comment(0)
R
1

Your problem goes away if you replace your:

DateTime.Now

with:

DateTime.Today

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

Rosierosily answered 3/12, 2009 at 10:57 Comment(0)
A
0

I normally use the following code to get the output as intended by the unit in which the output is required:

        DateTime[] dd = new DateTime[] { new DateTime(2014, 01, 10, 10, 15, 01),new DateTime(2014, 01, 10, 10, 10, 10) };

        int x = Convert.ToInt32((dd[0] - dd[1]).TotalMinutes);

        String unit = "days";

        if (x / 60 == 0)
        {
            unit = "minutes";
        }

        else if (x / 60 / 24 == 0)
        {
            unit = "hours";
            x = x / 60;
        }

        else
        {
            x = x / (60 * 24);
        }

        Console.WriteLine(x + " " + unit);
Alenealenson answered 15/4, 2014 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.