Simple way to handle time in C#?

前端 未结 4 1492
囚心锁ツ
囚心锁ツ 2020-12-18 08:01

My current approach is something like

DateTime startHour = new DateTime(1900,1,1,12,25,43);
DateTime endHour = new DateTime(1900,1,1,13,45,32);

// I need to         


        
相关标签:
4条回答
  • 2020-12-18 08:13

    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.

    0 讨论(0)
  • 2020-12-18 08:16

    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?

    0 讨论(0)
  • 2020-12-18 08:19

    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) {
        ...
    }
    
    0 讨论(0)
  • 2020-12-18 08:22

    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) {
        //...
    }
    
    0 讨论(0)
提交回复
热议问题