All*_*ang 4 .net c# silverlight
我想在天中有两个DateTimeOffset对象的差异(例如,检查差异是否小于40天)。
我知道可以通过将其更改为FileTime来完成,但是想知道是否还有更好的方法。
最简单的方法是相互减去偏移量。它返回一个TimeSpan您可以比较的。
var timespan = DateTimeOffset1 - DateTimeOffset2;
// timespan < TimeSpan.FromDays(40);
// timespan.Days < 40
Run Code Online (Sandbox Code Playgroud)
我倾向于将其添加到通过TimeSpan的另一种方法中的功能,因此,您不仅限于几天或几分钟,而还可以是一段时间。就像是:
bool IsLaterThan(DateTimeOffset first, DateTimeOffset second, TimeSpan diff){}
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果您喜欢流利的样式代码(在测试和配置之外,我不是一个忠实的拥护者)
public static class TimeExtensions
{
public static TimeSpan To(this DateTimeOffset first, DateTimeOffset second)
{
return first - second;
}
public static bool IsShorterThan(this TimeSpan timeSpan, TimeSpan amount)
{
return timeSpan > amount;
}
public static bool IsLongerThan(this TimeSpan timeSpan, TimeSpan amount)
{
return timeSpan < amount;
}
}
Run Code Online (Sandbox Code Playgroud)
将允许类似:
var startDate = DateTimeOffset.Parse("08/12/2012 12:00:00");
var now = DateTimeOffset.UtcNow;
if (startDate.To(now).IsShorterThan(TimeSpan.FromDays(40)))
{
Console.WriteLine("Yes");
}
Run Code Online (Sandbox Code Playgroud)
上面写着“如果从开始日期到现在的时间短于40天”。
| 归档时间: |
|
| 查看次数: |
5544 次 |
| 最近记录: |