Displaying a Date in HTML without a NET


For years now, I’ve worked in ASP.NET, which provides a lot of assistance – thus it’s reason to exist. Sometimes, unknowingly to me, I lose site of what all .NET is doing for me. Take for example, displaying a date. For the ASP.NET guy, one would go to the master page, setup a HTML element that is shown on every page, and call some server-side code leveraging System.DateTime.Now.ToString(format) and done!

Well, today, a non-technical friend of mine asked how to display a date when they don’t have a web framework to fall back on. So, I thought this would be an easy endeavor to dig up a little Javascript and show a quick way to do this. For most of you who live in the land of mature web development, you can stop reading this now.

First, I made a set of Javascript to do the work for me (tons of examples all over the internet), and put this in a file. Note that a lot of Javascript samples call document.write and just dump a date variable. I wanted to have a way to display the date in a specific place, so my function, JB_DisplayDate takes a parameter of the element (a SPAN or DIV), and then loads the date into that region.

    1: var now = new Date();
    3: var days = new Array(
    4:         'Sunday', 'Monday', 'Tuesday',
    5:         'Wednesday', 'Thursday', 'Friday', 'Saturday');
    7: var months = new Array(
    8:         'January', 'February', 'March', 'April', 'May',
    9:         'June', 'July', 'August', 'September', 'October',
   10:         'November', 'December');
   12: var date = ((now.getDate() < 10) ? "0" : "") + now.getDate();
   14: function fourdigits(number) {
   15:     return (number < 1000) ? number + 1900 : number;
   16: }
   18: function JB_DisplayDate(dateElement) {
   20:     today = days[now.getDay()] + ", " +
   21:         months[now.getMonth()] + " " +
   22:         date + ", " +
   23:           (fourdigits(now.getYear()));
   25:     if (document.getElementById)
   26:         document.getElementById(dateElement).innerHTML = today;
   28: }

Since I stored the functions in a Javascript file (because my friend needs to call from multiple HTML files.) Therefore, the calling page needs to know about this Javascript file. Very simply, the following goes into the HEAD element:

    1: <script type="text/javascript" src="Scripts/JB-DateTime.js"></script>

You’ll need a place on the screen obviously to show the date. In my simple case, I did the following:

    1: <span id="spanClock">1</span> 


Next, something on the page has to call the function. While there are several ways to do this, I decided to leverage the browser’s ONLOAD event, like the following. So, when the page displays, the date will be shown.

    1: <body onload="JB_DisplayDate('spanClock');">


That’s it. I know this is a simple example, but wanted to see if I could get it figured out.

I’d much rather do this with ASP.NET!