Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 292
Daniel Garcia Sanchez Avatar asked Apr 18 '13 10:04

Daniel Garcia Sanchez


People also ask

How do you check if a date is between two dates?

To check if a date is between two dates:Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.

How do you check a date lies between two dates in JS?

To check if one date is between two dates with JavaScript, we can compare their timestamps. const currentDate = new Date(). toJSON(). slice(0, 10); const from = new Date("2022/01/01"); const to = new Date("2022/01/31"); const check = new Date(currentDate); console.

Is a date between two dates Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.

How do you check if date is within a certain range in JavaScript?

Answers. var currentDate = new Date(); var minDate = new Date('01/01/1753'); var maxDate = new Date('12/31/9999'); if (currentDate > minDate && currentDate < maxDate ){ alert('Correct Date') } else{ alert('Out Side range !! ') }


1 Answers

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) 
like image 111
Diode Avatar answered Sep 25 '22 05:09

Diode