C#最好的方法来比较一天的两个时间 [英] C# best way to compare two time of the day

查看:121
本文介绍了C#最好的方法来比较一天的两个时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一天中的指定时间是否过去。我真的不喜欢我在做的事情:

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

内部静态bool IsTimeOver()
{
返回DateTime.Now.TimeOfDay.Subtract(_whenTimeIsOver).Ticks> 0;
}

你好吗?

解决方案

如何:

 内部静态bool IsTimeOver()
{
return DateTime.Now.TimeOfDay> _whenTimeIsOver;
}

运算符重载对日期和时间工作非常有帮助:)您可能还想考虑使它成为一种财产而不是一种方法。



很不幸的是,没有一个

  DateTime.CurrentTime 

  TimeSpan.CurrentTime 

避免 DateTime.Now.TimeOfDay (就像 DateTime.Today ),但唉,没有...



我在 int 中有一组扩展方法/ csharp / miscutilrel =noreferrer> MiscUtil ,它将初始化 _whenTimeIsOver neater - 你会使用:

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

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


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?

解决方案

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

I have a set of extension methods on int in MiscUtil which would make the initialization of _whenTimeIsOver neater - you'd use:

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

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

这篇关于C#最好的方法来比较一天的两个时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆