Skip to content Skip to sidebar Skip to footer

How To Compare Current Time Against Time Of Day

I have an ASP.net page which has different hours of operation for different day. What I am looking to do is compare the current time against today's open to close hours. If the cur

Solution 1:

I modified the server side code to create two String variables that you can call from the client side using the server tags. Just place them in the url for the background. (I assume that's the location of the image you want to change).

public partial class medical_specialties : System.Web.UI.Page
{
    String url1 = "theImages/ClosedHeaderMiddle.png";
    String url2 = "theImages/OpenHeaderMiddle.png";
    String location1URL = "";   //White Plains
    String location2URL = "";   //Rye
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime now = DateTime.Now;
        string time = now.ToString("T");
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + time + "');", true);

            if(now.DayOfWeek == DayOfWeek.Monday){
                if(IsTimeOfDayBetween(now, new TimeSpan(7, 0, 0), new TimeSpan(8, 0, 0) )) {
                    location1URL = url2;
                    location2URL = url1;
                } else if(IsTimeOfDayBetween(now, new TimeSpan(8, 0, 0), new TimeSpan(17, 30, 0)) {
                    location1URL = url2;
                    location2URL = url2;
                } else if(IsTimeOfDayBetween(now, new TimeSpan(17, 30, 0), new TimeSpan(19, 30, 0)) {
                    location1URL = url2;
                    location2URL = url1;
                } else {
                    location1URL = url1;
                    location2URL = url1;
                }
            } else if(now.DayOfWeek == DayOfWeek.Tuesday) {
                ..... //just go on like the example above
            }

    }
}

//Credit: this following static function is from: https://stackoverflow.com/a/592258/2777098 (@Daniel LeCheminant)

static public bool IsTimeOfDayBetween(DateTime time, 
                                      TimeSpan startTime, TimeSpan endTime)
{
    if (endTime == startTime)
    {
        return true;   
    }
    else if (endTime < startTime)
    {
        return time.TimeOfDay <= endTime ||
            time.TimeOfDay >= startTime;
    }
    else
    {
        return time.TimeOfDay >= startTime &&
            time.TimeOfDay <= endTime;
    }

}

Post a Comment for "How To Compare Current Time Against Time Of Day"