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.

4

4 回答 4

13
int days = (int)Math.Ceiling(diff.TotalDays);
于 2009-12-03T10:26:39.707 回答
1

如果您更换以下设备,您的问题就会消失:

DateTime.Now

和:

DateTime.Today

因为您的差异计算将在一整天内工作。

于 2009-12-03T10:57:10.720 回答
1

这个问题相当哲学。如果圣诞节是明天,你会认为还剩 1 天,还是还剩 0 天。如果您将明天的日期计算在内,答案将为 0。

于 2009-12-03T10:32:54.617 回答
0

我通常使用以下代码来获取需要输出的单元所期望的输出:

        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);
于 2014-04-15T10:21:57.910 回答