Daniel Garcia Sanchez Daniel Garcia Sanchez - 1 year ago 87
Javascript Question

check if one date is between two dates (javascript)

I need one thing,
I need check if one date, that is a string in fomat dd/mm/yyyy
is contained between two dates, with the same format (dd/mm/yyyy)

I tried this, but 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 check,to and from variables have isNaN value
Could you help me, please?
Best regards, Daniel

Answer Source

Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For that either you have to use a library like moment.js or do something as given 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], d1[1]-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], d2[1]-1, d2[0]);
var check = new Date(c[2], c[1]-1, c[0]);

console.log(check > from && check < to)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download