Simple way to handle time in C#?

坚强是说给别人听的谎言 提交于 2019-11-29 07:27:13
Jon Skeet

It's not at all clear what you mean by "is greater than startHour"... but taking

TimeSpan startHour = new TimeSpan(12, 25, 43);
if (endHour.TimeOfDay > startHour)
{
    ...
}

... works pretty simply.

By all means add argument checking to make sure that you don't specify a value for startHour which is < 0 or > 23 hours, but that's all pretty easy.

.NET's date and time API is quite primitive (even in 3.5) compared with, say, Joda Time - but in this particular case I think it's not too bad.

A little hint - .NET supports arithmetic operations on DateTime objects, and returns a TimeSpan object. Thus, you can do the following:

DateTime fromDate = ....
DateTime toDate = ....
TimeSpan diff = toDate - fromDate;

and you can expand this to:

DateTime fromDate = DateTime.Now;
DateTime toDate = DateTime.Now.addMinutes(x);

if ((toDate - fromDate).TotalMinutes > 15) {
    ...
}

You should use TimeSpan for startHour and endHour. When comparing with now, you should "convert" them to a full DateTime or get the Time with DateTime.TimeOfDay as mentioned by Jon Skeet.


TimeSpan startHour = new TimeSpan(12, 25, 43);
DateTime now = DateTime.Now;

if (now.CompareTo(DateTime.Today.Add(startHour)) > 0) {
    //...
}

or


TimeSpan startHour = new TimeSpan(12, 25, 43);
DateTime now = DateTime.Now;

if (now.TimeOfDay.CompareTo(startHour) > 0) {
    //...
}

So you're only interested in the time component of the date.

if(DateTime.Now.TimeOfDay > startHour.TimeOfDay)
{
  // do stuff
}

What's wrong with doing this?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!