Related Posts

Archive

Until we actually care: Faking a Javascript Timestamp

February 19th, 2007

The scenario is this:

There is a page on CC Corp’s website that employees can go to to check if they have to come to work that day. The actual page is in HTML - so no server side scripting. However, the appreciably lazy admin does not want to touch the page the 363 days of the year that people have to come to work.

But to not look lazy, the page’s update time must be relatively recent.

Enter JavaScript’s Date object.


The JavaScript Date Object, at its core, counts the seconds since the beginning of the Unix Epoch. There is one very important thing about this measure - it doesn’t care about time zones or leap years.

However, since accumulated seconds is not very useful, so JavaScript gives options to print it in a human-friendly format.

For this code:
<script type="text/javascript">document.write(Date());</script>
your browser uses the format:

Of course, the actual format varies, so there are additional functions to get the current Second, Hour, Year, and other such things. There are also functions to set them. A full list can be found on W3Schools.

And Here is my Working Code.

Let’s walk through it:

First, I define arrays of the names of days and months. Read “Here is where you can localize the function”.

Next, I store today’s date in today - JavaScript gets it form the computer’s system clock.

modified is taken from the server headers sent along with the page. As some servers do not send this information, there should be a test of some sort to make sure the value is not zero. Also notice that it takes some more work to get it working consistently.

Now I set a time in today - 5:01 in the morning. Since the page should never be modified after right now, but should be modified somtime in the last day, this is a decent arbitrary value.

Now I define an empty array called markupBuilder, which will be used to store the time displayed on the page. I could use a string and the “+=” operator, but that is not very efficient.

Here comes out test. Has the page been edited since 5:01 this morning? (Which 5:01? EST? I don’t really care.)

Build our string.

And finally write our string, right after collapsing the array. If this were a newer page, this could have been done in the DOM, somtime during the window.onload - all there is to add to the code is an ID attribute for easy reference.

Posted in JavaScript |

Comments are closed.

Previous post: Vista fonts available

Next Post: Some easy field validators