Javascript has a pretty basic Date object. It is cool but not as cool as in other languages. In fact, it is different but we like it anyway.

The primitive value

A date is nothing else than the number of millisecond since January 1, 1970 00:00:00. So now is 1 177 603 737 358.

When you create a Date object, it is initialized at now. To alert the primitive value (the number of milliseconds since 1970), I simply do.

var now = new Date();
  alert(now.valueOf());

Adding and subtracting

Note : You have to know that months in javascript are 0 = january and 11 = december. Just like Java.

This one is easy. When I want to add a number of days (or anything else) to a date, I use the getDate() and setDate() function. When you don't know that the setDate() function (and setHours, setMinutes, setMonths…) has some magic in it, you may have a hard time manipulating the dates.

So, I want to add 3 days to the current date.

var now = new Date();// Add 3 days
  now.setDate(now.getDate() + 3);
  alert(now);
The problem is when you want to add 3 days to December 31 2006, it should return January 3 2007. No problemo!
var now = new Date();

// Set to December 31 2006 now.setYear(2006); now.setMonth(11); now.setDate(31);

// Add 3 days now.setDate(now.getDate() + 3);

alert(now);

You see that the date is correctly computed. You can do the same things with all the other parts of the date. Magic is in the air!

No formatting

There's no way of formatting a date to a string except if you use concatenation.

If you want to display the YYYY-MM-DD format, you'll have to do this ugly code.

var now = new Date();var nowStr = now.getFullYear().toString() + "-" +
      (now.getMonth()+1 < 10 ? "0" + (now.getMonth()+1).toString() : (now.getMonth()+1).toString()) + "-" +
      (now.getDate() < 10 ? "0" + now.getDate().toString() : now.getDate().toString());

alert(nowStr);

Maybe you won't do it as ugly as this but it won't look pretty. Maybe you should check for a librairy.

The Date.parse() function

Don't use the Date.parse() function. I don't even know which format it takes. It looks like month[sep]day[sep]year but I'm not sure. Better use some regexp and use the setDateUnit function accordingly.

getYear() VS getFullYear()

You should not use the getYear() function. For an obscure reason, it returns the number of years since 1900. You don't want to use it. Trust me.

You are now a master

That's what you need to know about javascript Date object, you are now mastering it.

Do you have something else to add?

comments powered by Disqus