Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if current datetime is between 08 PM and 08 AM and calculate total hours left until 08 AM

Tags:

c#

datetime

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?
}
like image 346
user2818430 Avatar asked Sep 08 '17 05:09

user2818430


1 Answers

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;
}
like image 67
Zohar Peled Avatar answered Sep 19 '22 11:09

Zohar Peled