JavaScript Date Difference Using Format Yyyy-mm-dd

Finding date differences in JavaScript Date objects is trivial but it takes a turn when dealing with multiple timezones. Well, that is up for another discussion but for now, let’s consider 2 cases of finding differences between two dates using the below date formats.

Using date format - mm/dd/yyyy & yyyy-mm-dd to find the difference

Difference between using mm/dd/yyyy & yyyy-mm-dd
1
2
3
4
5
6
7
8
9
10
11
var start_date = new Date('12/01/2013'),
    end_date   = new Date(),
    one_day_in_milliseconds = 1000*60*60*24,
    date_diff = Math.floor( ( end_date.getTime() - start_date.getTime() )/one_day_in_milliseconds ) ;

    console.log("Result 1 - Date difference between ",end_date, " & ",start_date, " - ", date_diff);

var s_date = new Date('2013-12-01'),
    date_diff_2 = Math.floor( ( end_date.getTime() - s_date.getTime() )/one_day_in_milliseconds ) ;

    console.log("Result 2 - Date difference between ",end_date, " & ",s_date, " - ", date_diff_2);

You may notice that the difference between both these ways differs by 1. If this is the case and you’re using the second format [yyyy-mm-dd], then you can solve this using the following technique.

Solution

Difference between 2 dates using yyyy-mm-dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getNewDate(dateString){

  var date = dateString ? new Date(dateString) : new Date(),
      timezoneOffset = date.getTimezoneOffset();

      return new Date( date.getTime() + timezoneOffset*60*1000*(dateString?1:0) );
}

var start_date = getNewDate('2013-12-01'),
    end_date   = getNewDate(),
    one_day_in_milliseconds = 1000*60*60*24,
    date_diff = Math.floor( ( end_date.getTime() - start_date.getTime() )/one_day_in_milliseconds ) ;

    console.log("Date difference between ",end_date, " & ",start_date, " - ", date_diff);

Here, we are considering the timezone offset when a new Date object is created using dateString in the format yyyy-mm-dd.

Post a Comment

Previous Post Next Post