qua1ity qua1ity - 1 year ago 102
Javascript Question

Check if a date is between two dates

I have an array with different dates with the format of year-month-day.

something like this:

var dates = ["2016-08-01", "2016-08-09", "2016-08-10", ....];

I also have a function that formats todays date in the same format as above. And is stored in a variable:

var currentDate; //Contains current date in the format of year-month-day

What i need to do is to check if any of the dates in the array, either:

  • Match with today's date.- e.g. Today would be 2016-08-13

  • Match with 14 days back from today's date. - e.g. 14 days back from today (2016-08-13) would be 2016-07-30

  • Or match with any dates between the current and 14 days back.

I'm trying to do this by looping through the array, checking each value. But im unsure about the if condition/conditions

for(var i = 0; i < dates.length; i++) {
if(currentDate === *condition*) {

Anyone have a good solution for this? Thanks in advance!

Answer Source

Firstly, create a new Date() from your currentDate ( currentDate is string format Y-d-m with hour and minutes is 00:00)

var current = new Date(currentDate);
var matchWithCurrent = [];
var matchWithDayBack = [];
var between = [];

just loop through your date array

for (var i=0; i<dates.length; i++) {

    var tmpDate = new Date(dates[i]); //Convert string to date
    var diff = Math.ceil((current - tmpDate) / (1000 * 3600 * 24)); //get time difference (current - tmpDate is milisecond, we need convert it to day)

    // Check condition and push it on array correct

    if (diff == 0) {

    if (diff == 14) {

    if ((diff > 0) && (diff <14)) {



If you want only one array match with 3 condition just check 3 condition in only one if and push it into your result array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download