Thursday, June 9, 2011

Working with Dates in JavaScript

JavaScript is a great, often very quick, client side language that has the power to allow you to do a lot of cool things without trips to the server and back. That makes it very useful for a lot of things, but, also makes it very fickle, because it is client dependent. OK, we all know that already...so I'll move on.

Working with dates (and time, but time is not part of my post this time) can be very frustrating when it has to be validated, depending on how you need to validate.

Validating it for proper format is easy, a simple regular expression can validate a YYYY-MM-DD type of format (or any other):

re = /^\d{4}\-\d{2}\-\d{2}$/;
if(!date_string.match(re))
{
alert("not proper formatting");
}
Pretty simple, right?

OK, but what if you need to compare dates, such as making sure the start date is before the end date in some sort of a date range query? First, bust it up into pieces of year, month and day at the delimiter, which is usually a - or / or ., so, just split it on that, for starters.
var dt = date_string.split("-");
After that, the sections of the variable array are the different pieces. If it's a YYYY-MM-DD format, the year would be dt[0], the month would be dt[1] and the day would be dt[2]. From here you need to put these variable into JavaScript's Date object...but wait, here is where one of the stupidest things come into play...the "day" uses a 01 to 31 type of index...but month does not, it's not 01 to 12 like one would think, it's actually 00 to 11...so, before passing month into the Date object, be sure to subtract 1.
test_date = (new Date(dt[0], parseInt(dt[1]-1), dt[2]));
Quite often this detail may not matter as comparisons are still all relative...however, if you want to test and make sure the selected date is not in the future, it will give you problems. However, after putting a date into this Date object, you can then compare them as true dates, using greater than and less than operators to determine which is later than the other.

The last solution I will cover will be to determine if the entered date is actually a real date...think about somebody trying to pass in something like 2011-02-30...that would pass a simple formatting test, and within the range of most acceptable month and day ranges...so, with the function below, you pass in your date, in three variable, year, month and day, by splitting it as mentioned above, it will take those three, and then turn it into a JavaScript date object, then use JavaScript to get the year, month and day from that object...then compare the original year, month and day to the object derived year, month and day.

function isDateValid(year, month, day)
{
month = month - 1;
mSeconds = (new Date(year, month, day)).getTime();
objDate = new Date();
objDate.setTime(mSeconds);
if (objDate.getFullYear() != year || objDate.getMonth() != month || objDate.getDate() != day)
{
return false;
}
return true;
}

So, how does that work for ya?