C# 获取 DateTime.Now 和某个 DateTime 之间的总天数(int)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19348798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:48:45  来源:igfitidea点击:

Get total days (int) between DateTime.Now and a certain DateTime

c#linqdatetime

提问by user2818430

How can I get the total days as int between DateTime.Now and a specific DateTime? Can this be done using LINQ?

如何获得 DateTime.Now 和特定 DateTime 之间的 int 总天数?这可以使用 LINQ 来完成吗?

采纳答案by Willem Van Onsem

You can simply calculate the difference using the following method:

您可以使用以下方法简单地计算差异:

DateTime a = ;//some datetime
DateTime now = DateTime.Now;
TimeSpan ts = now-a;
int days = Math.Abs(ts.Days);

回答by Cyral

Simply subtract two DateTimes from each other, into a TimeSpan, and get the TotalDayscomponent from it.

简单地将两个DateTimes相减,变成 a TimeSpan,然后从中获取TotalDays组件。

TimeSpan diff = DateTime.Now - OtherDateTime
int days = (int)Math.Abs(Math.Round(diff.TotalDays));

It is rounded to remove the fraction caused by the hours/minutes/seconds, and the absolute value is given so you get the exact change.

它被四舍五入以去除由小时/分钟/秒引起的分数,并给出绝对值以便您获得确切的变化。

回答by Alireza

In Linq2Object:

Linq2Object 中

DateTime.Now.Subtract(yourDateTime).TotalDays

In Linq2Entites:

Linq2Entites 中

     EntityFunctions.DiffDays(DateTime.Now, yourDateTime)