C# - 两个日期之间的差异?
我正在尝试计算两个日期之间的差异。这就是我目前正在使用的:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个问题相当哲学;如果明天就是圣诞节,你会认为还剩下 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.
那么您的问题就会消失,
如果您将您的:替换为:,
因为您的差异计算将在整天内有效。
Your problem goes away if you replace your:
with:
as your difference calculation will then be working in whole days.
我通常使用以下代码来获取需要输出的单元的预期输出:
I normally use the following code to get the output as intended by the unit in which the output is required: