Mastering the date object in javascript
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() < 10 ? "0" + now.getMonth().toString() : now.getMonth().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 set[DateUnit]() 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?


For more questions on the date object, you may look here:
http://www.irt.org/script/date.htm
I’m not 100% sure that JS really uses POSIX time representation but it may be the case and if so (and if someone can confirm), here is an interesting link: http://en.wikipedia.org/wiki/Year_2038_problem
One thing I have done with the date formatting is I will create a new prototype property for the format that I want. Prevents me from repeating the gobbeldy-gook over and over and improves readability.
Date.prototype.toYYYYMMDD = function() {
return this.getFullYear().toString() + "-" +
(this.getMonth()
Since that got cut off, try http://pastie.caboo.se/57443 for the example
I’ve always found it odd how some developers create an Array of days in a month and may do a leap year check to if position 1 of the array is 28 or 29.
Unless I’m incorrect why not this?
Date.prototype.getMonthDays = function(month) {
var temp_date = new Date(this.getFullYear(), this.getMonth()+1, 1);
temp_date.setDate(temp_date.getDate()-1);
return temp_date.getDate();
};
Works no matter if the year is leap or not. And gets rid of that useless array.
Along the same lines as your way of adding dates, some people have troubles knowing if a month has 31, 30, 28, or 29 days in it. They typically devise elaborate sets of arrays and calculations for number of days in a given month depending on if it’s a leap year, etc.
It’s surprisingly easy to get the info; you just set the following month’s day = 0. 12/0/2007 === 11/30/2007
To find out how many days are in the current month:
[code]
var now = new Date();
now.setMonth(now.getMonth() + 1);
now.setDate(0);
alert(now.getDate());
[/code]
@Jon
This is a great tip! I’ll remember it…
Dates are unusable when dealing with anything before 1970, so if you deal with birthdate input and need to calculate an age on the client side, don’t use Date to help with the arithmetic. I found it’s best to calculate age from separate year/month/day integers.
I’ve been using Matt Kruse’s date formatting library and I find it works quite well. It definitely beats using string concatenation.
http://www.mattkruse.com/javascript/date/source.html
Hi Dan,
We’ve been working on a JavaScript Date library for a while that you might find useful.
http://www.datejs.com/
One major piece of functionality we include is a new Parser.
Parsing Example
alert(Date.parse(”next friday”));
Here’s a couple other samples which may be relevant to your samples.
Formatting Example
alert(new Date(”yyyy-MM-dd”));
Add/Subtract Example
new Date().add(5).days();
Date.today().add(-5).months();
Hope this helps.