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 classmedical_specialties : System.Web.UI.Page
{
    Stringurl1="theImages/ClosedHeaderMiddle.png";
    Stringurl2="theImages/OpenHeaderMiddle.png";
    Stringlocation1URL="";   //White PlainsStringlocation2URL="";   //RyeprotectedvoidPage_Load(object sender, EventArgs e)
    {
        DateTimenow= DateTime.Now;
        stringtime= now.ToString("T");
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + time + "');", true);if(now.DayOfWeek == DayOfWeek.Monday){
                if(IsTimeOfDayBetween(now, newTimeSpan(7, 0, 0), newTimeSpan(8, 0, 0) )) {
                    location1URL = url2;
                    location2URL = url1;
                } elseif(IsTimeOfDayBetween(now, newTimeSpan(8, 0, 0), newTimeSpan(17, 30, 0)) {
                    location1URL = url2;
                    location2URL = url2;
                } elseif(IsTimeOfDayBetween(now, newTimeSpan(17, 30, 0), newTimeSpan(19, 30, 0)) {
                    location1URL = url2;
                    location2URL = url1;
                } else {
                    location1URL = url1;
                    location2URL = url1;
                }
            } elseif(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)
    {
        returntrue;   
    }
    elseif (endTime < startTime)
    {
        returntime.TimeOfDay <= endTime ||
            time.TimeOfDay >= startTime;
    }
    else
    {
        returntime.TimeOfDay >= startTime &&
            time.TimeOfDay <= endTime;
    }

}

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