Dating a blog

The simple blog we create is so cute, that we decide give it a few improvements.

First of all, what's a blog without a date for each post? Managing dates it's a common task, so JavaScript provides a class for doing that, Date.

There are a few alternative constructors for a Date object: we can call the no-argument one creates a date for the moment we call it; or we can pass it year, month, day, ... all of them as integer (but remember: January is the month number 0, and December is 11), or we can pass the date as a string, in american format (month/day/year).

Once we have a Date object we can convert it in a readable string using a few method, toDateString() is one of them, providing a representation that is often what we are looking for.

Let's rewrite our BlogEntry class having a Date among its properties. We want preserve the existing code, so we are ready for the case the constructor is passed without specifying a date. In this case, from the point of view of the JavaScript interpreter, we say that the type of the passed date is undefined. For better robustness of our code we check also if the passed date is null, in both case we translate that as a user request to use the current date:

function BlogEntry(title, body, date) {
this.title = title;
this.body = body; = (typeof(date) == "undefined" || date == null) ? new Date() : date;

this.toString = function() {
return this.title + " (" + + "): " + this.body;

this.toHTML = function() {
return "<b><i>(" + + ")</i> " + this.title +
"</b><br />" + this.body;

Now we change our predefined blog entries:

var blog = [ new BlogEntry("Welcome", "Welcome to my new blog", new Date(2005, 11, 31)),
new BlogEntry("Last one", "Today's news"),
new BlogEntry("Again me!", "Many things to say", new Date("01/02/2006")),
new BlogEntry("Summertime", "I'm so <b>busy</b>!", new Date("07/15/2007")) ];

And we enjoy the view.

More information on the JavaScript Object Oriented features in chapter nine of Head First JavaScript. The code here is heavily based on an example you can find in this fun and useful book.

No comments:

Post a Comment