0

I have a DateTime object with DateTime stored within it.

How would I take that DateTime and compare its time so I can check whether the time within that DateTime is greater, or less than 11:00:00 or 20:00:00 etc?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Izacch
  • 383
  • 3
  • 10

4 Answers4

4

TimeOfDay is what you can use;

DateTime today = DateTime.Now;
TimeSpan timeCheck = (7,0,0)    //07:00 
If(today.TimeOfDay > timeCheck)
{
   //do something
}

or you could also use Hour that gets the hour component of the date in a way;

    DateTime today = DateTime.Now;
    If(today.Hour > 6)
    {
       //do something
    }
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • This looks like the right thing! My only concern is the timeCheck being (7,0,0) and commented as 7:00PM. How would I change it to AM or PM? – Izacch Apr 17 '18 at 07:36
  • @Izacch there: https://stackoverflow.com/questions/13044603/convert-time-span-value-to-format-hhmm-am-pm-using-c-sharp – DirtyBit Apr 17 '18 at 07:41
  • Many thanks this is perfect! – Izacch Apr 17 '18 at 13:28
2

You can try using TimeOfDay:

  DateTime source = DateTime.Now;

  if (source.TimeOfDay >= new TimeSpan(11, 0, 0) &&
      source.TimeOfDay <= new TimeSpan(20, 0, 0)) {
    ...
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • @Tim Schmelter: I've put it just for generalization, when we want to check, say, `11:45` and `20:10`; in this particular case I agree that `source.Hour` is a better choice. – Dmitry Bychenko Apr 17 '18 at 07:37
0

Try the DateTime.CompareTo Method (DateTime).

https://msdn.microsoft.com/en-us/library/5ata5aya(v=vs.110).aspx

Vlam
  • 1,622
  • 1
  • 8
  • 17
0

Here is another approach.

        DateTime dt = DateTime.Now;
        int[] timeOnly = Array.ConvertAll(dt.ToString("HH:mm:ss").Split(':'), int.Parse);
        TimeSpan ts = new TimeSpan(timeOnly[0],timeOnly[1],timeOnly[2]);
          if (ts >= new TimeSpan(11, 0, 0) && ts <= new TimeSpan(20, 0, 0)) {
              Console.WriteLine("InBetween");
  }
        else
            Console.WriteLine(dt.ToString("HH:mm:ss"));

Proof of work

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44