Here is the scenario, I need to know if current DateTime is between 08:00 PM (20:00) and 08:00 AM (08:00). If yes, I need to get the total hours left until 08:00 AM (08:00).
My attempt:
TimeSpan start = TimeSpan.Parse("20:00");
TimeSpan end = TimeSpan.Parse("08:00");
TimeSpan now = DateTime.Now.TimeOfDay;
bool flag = false;
if (start <= end)
{
if (now >= start && now <= end)
{
flag = true;
}
}
else
{
if (now >= start || now <= end)
{
flag = true;
}
}
if (flag)
{
/// calculate hours?
}
Here is one simple way to do it:
var date = DateTime.Now;
if(date.Hour >= 20 || date.Hour < 8)
{
var DateTime8 = date.Date.AddHours((date.Hour > 8) ? 24 + 8 : 8);
TimeSpan diff = DateTime8 - date;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With