C# - Difference between two dates?

北慕城南 提交于 2019-12-01 15:49:18

问题


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.


回答1:


int days = (int)Math.Ceiling(diff.TotalDays);



回答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.




回答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.




回答4:


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


来源:https://stackoverflow.com/questions/1839025/c-sharp-difference-between-two-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!