javascriptdate

Check if one date is between two dates


I need to check if a date - a string in dd/mm/yyyy format - falls between two other dates having the same format dd/mm/yyyy

I tried this, but it doesn't work:

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";

var from = Date.parse(dateFrom);
var to   = Date.parse(dateTo);
var check = Date.parse(dateCheck );

if((check <= to && check >= from))      
    alert("date contained");

I used debugger and checked, the to and from variables have isNaN value. Could you help me?


Solution

  • Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below

    var dateFrom = "02/05/2013";
    var dateTo = "02/09/2013";
    var dateCheck = "02/07/2013";
    
    var d1 = dateFrom.split("/");
    var d2 = dateTo.split("/");
    var c = dateCheck.split("/");
    
    var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
    var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
    var check = new Date(c[2], parseInt(c[1])-1, c[0]);
    
    console.log(check > from && check < to)