Wednesday, December 14, 2011

Javascript: Is date in range?

Today I encountered a little problem wich I had to solve with dates. I had to check, if today has a special event. The range is stored in a simple date format: YYYY.MM.DD-YYYY.MM.DD

Here is the solution:

var nowDate = new Date(2011, 12, 14).getTime();

var startDate = new Date(2011, 12, 13).getTime();
var endDate = new Date(2012, 1, 5).getTime();

if (startDate <= nowDate && nowDate <= endDate) {
 alert('It\'s in range!');
}


The "getTime()" method will create a timestamp from the created date. It's like a date in a number format wich can be easily compared to eachother.

1 comment:

  1. Hi,

    Silly question, but shouldn't the month be in the range 0-11?

    John

    ReplyDelete