C# 比较一天中两个时间的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1411125/
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-06 16:15:41  来源:igfitidea点击:

C# best way to compare two time of the day

c#datetimetimespan

提问by Toto

I woulld like to know if a specified time of the day is passed. I don't really like the way I am doing:

我想知道一天中的指定时间是否已过。我真的不喜欢我做的方式:

private static readonly TimeSpan _whenTimeIsOver = new TimeSpan(16,25,00);

internal static bool IsTimeOver()
{
    return DateTime.Now.TimeOfDay.Subtract(_whenTimeIsOver ).Ticks > 0; 
}

How do you do?

你好吗?

采纳答案by Jon Skeet

How about:

怎么样:

internal static bool IsTimeOver()
{
    return DateTime.Now.TimeOfDay > _whenTimeIsOver;
}

Operator overloading is very helpful for date and time work :) You might also want to consider making it a property instead of a method.

运算符重载对于日期和时间工作非常有帮助 :) 您可能还需要考虑将其设为属性而不是方法。

It's a slight pity that there isn't a

有点遗憾没有

DateTime.CurrentTime

or

或者

TimeSpan.CurrentTime

to avoid DateTime.Now.TimeOfDay(just as there's DateTime.Today) but alas, no...

避免DateTime.Now.TimeOfDay(就像那里一样DateTime.Today)但是唉,不......

I have a set of extension methods on intin MiscUtilwhich would make the initialization of _whenTimeIsOverneater - you'd use:

intMiscUtil 中有一组扩展方法,可以使初始化_whenTimeIsOver更整洁 - 您可以使用:

private static readonly TimeSpan _whenTimeIsOver = 16.Hours() + 25.Minutes();

It's not to everyone's tastes, but I like it...

不是每个人的口味,但我喜欢它......

回答by Philippe Leybaert

if (DateTime.Now.TimeOfDay > _whenTimeIsOver)
    ....