C# - 两个日期之间的差异?

发布于 2024-08-12 21:30:44 字数 348 浏览 9 评论 0原文

我正在尝试计算两个日期之间的差异。这就是我目前正在使用的:

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";

一切正常,除了休息一天。我假设这是因为它不计算一整天少于 24 小时的时间。有没有办法让它这样做?谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

茶花眉 2024-08-19 21:30:44
int days = (int)Math.Ceiling(diff.TotalDays);
int days = (int)Math.Ceiling(diff.TotalDays);
红尘作伴 2024-08-19 21:30:44

这个问题相当哲学;如果明天就是圣诞节,你会认为还剩下 1 天,还是还剩下 0 天。如果你把明天算进去,答案就是 0。

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.

慕烟庭风 2024-08-19 21:30:44

那么您的问题就会消失,

DateTime.Now

如果您将您的:替换为:,

DateTime.Today

因为您的差异计算将在整天内有效。

Your problem goes away if you replace your:

DateTime.Now

with:

DateTime.Today

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

自在安然 2024-08-19 21:30:44

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

        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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文