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?
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?
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
}
You can try using TimeOfDay:
DateTime source = DateTime.Now;
if (source.TimeOfDay >= new TimeSpan(11, 0, 0) &&
source.TimeOfDay <= new TimeSpan(20, 0, 0)) {
...
}
Try the DateTime.CompareTo Method (DateTime).
https://msdn.microsoft.com/en-us/library/5ata5aya(v=vs.110).aspx
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"));