Wednesday, January 28, 2009

C# Timespan in Web page

A few weeks back we had some serious weather problems here in the Northwest. Snow normally doesn't last a day on the ground, but during these few weeks snow continued to blanket the ground.

This complicated driving for many of my Washington neighbors. Because I came from Detroit Michigan, driving in snow is like riding a bike. Once you learned how, you can do it when necessary.

My job is located downtown right off the Puget Sound, which is simply a valley, so when to get downtown from any direction accessible, you have to brave the hills downward. When the snow came the agency that I work for needed a banner that would tell the public that we are closed due to inclement weather. It would only need to display on a certain day between certain hours and disappear.

This is the code I wrote:

</asp:Panel ID="Weather" runat="server" Visible="false">
<div style="color: Red; padding-left: 5px; padding-right: 5px; padding-bottom: 5px;padding-top: 5px; background-color: Black">
<span style="color: Yellow; font-weight: bold">Weather Alert!</span></br >

Due to Inclement Weather the Public Disclosure Commission will be Closing 12 noon
until 5pm Monday December 22, 2008.

</div>
</asp:Panel>

I placed a panel control with an ID="Weather" on the web page and set the visible default value to false so that it will not show when visitors first come to the site. I used style sheets to style the alert.

Next in the codebehind at the Page_Load level I used the Timespan class and created an instance of the class... heres the code.

TimeSpan ts = DateTime.Now.TimeOfDay;
if(ts.Hours >= 10 && ts.Hours <= 17 && DateTime.Now.Day == 22)
{
Weather.Visible = true;
}


As you can see the time span is between 10am and 5pm on 22nd of the month; it's important that you remove this completely from your page_load later otherwise it will appear every month on the 22nd. You can modify the code to include the month like this:

DateTime.Now.Month which is a type int;

Anyways, this worked great. Peace.

No comments: