Check if one date is between two dates

JavascriptDate

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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)

Solution 2 - Javascript

Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.

Something like

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

Solution 3 - Javascript

Try what's below. It will help you...

Fiddle : http://jsfiddle.net/RYh7U/146/

Script :

if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
    alert("Availed");
else
    alert("Not Availed");

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

Solution 4 - Javascript

The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.

var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1);  // -1 because months are from 0 to 11
var to   = new Date(d2);
var check = new Date(c);

alert(check > from && check < to);

This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/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]);


alert(check > from && check < to);

Solution 5 - Javascript

Simplified way of doing this based on the accepted answer.

In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.


var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to   = new Date('2020/01/31');
var check = new Date(currentDate);

console.log(check > from && check < to);

Solution 6 - Javascript

I have created customize function to validate given date is between two dates or not.

var getvalidDate = function(d){ return new Date(d) }
	
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
	return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}

Solution 7 - Javascript

Try this:

HTML

<div id="eventCheck"></div>

JAVASCRIPT

// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

// Add Zero if it number is between 0-9
if(dd<10) {
    dd = '0'+dd;
}
if(mm<10) {
    mm = '0'+mm;
}

var today = yyyy + '' + mm + '' + dd ;


// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017

// Add Zero if it number is between 0-9
if(endDay<10) {
    endDay = '0'+endDay;
} 
if(endMonth<10) {
    endMonth = '0'+endMonth;
}

// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//



// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
	document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)';  // true
} else {
	document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}

Fiddle: https://jsfiddle.net/zm75cq2a/

Solution 8 - Javascript

Here is a Date Prototype method written in typescript:

Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
  if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
  return !minDate ? true : this.getTime() >= minDate.getTime()
    && !maxDate ? true : this.getTime() <= maxDate.getTime();
};

Solution 9 - Javascript

I did the same thing that @Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone

e.g (the same code to example with array of dates)

var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.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 dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];

dates.forEach(element => {
   let parts = element.split("/");
   let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
        if (date >= from && date < to) {
           console.log('dates in range', date);
        }
})

Solution 10 - Javascript

Suppose for example your date is coming like this & you need to install momentjs for advance date features.

let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)

    let format = "MM/DD/YYYY";
    let startDate: any = moment().format(format);
    let endDate: any = moment().add(30, "days").format(format);
    let compareDate: any = moment(cmpDate).format(format);
    var startDate1 = startDate.split("/");
    var startDate2 = endDate.split("/");
    var compareDate1 = compareDate.split("/");

    var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
    var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
    var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);

    if (checkDate > fromDate && checkDate < toDate) {
      ... condition works between current date to next 30 days
    }

Solution 11 - Javascript

Try this

var gdate='01-05-2014';
        date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
        if(parseInt(date) < parseInt(Date.now()))
        {
            alert('small');
        }else{
            alert('big');
        }

Fiddle

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel Garcia SanchezView Question on Stackoverflow
Solution 1 - JavascriptDiodeView Answer on Stackoverflow
Solution 2 - JavascriptJasmine HowellView Answer on Stackoverflow
Solution 3 - JavascriptPandianView Answer on Stackoverflow
Solution 4 - Javascriptuser3109233View Answer on Stackoverflow
Solution 5 - JavascriptAndrew MykhalchukView Answer on Stackoverflow
Solution 6 - JavascriptKARTHIKEYAN.AView Answer on Stackoverflow
Solution 7 - JavascriptDoodlView Answer on Stackoverflow
Solution 8 - JavascriptNate MayView Answer on Stackoverflow
Solution 9 - JavascriptRafael SequeiraView Answer on Stackoverflow
Solution 10 - JavascriptMiyas MohammedView Answer on Stackoverflow
Solution 11 - JavascriptLal krishnan S LView Answer on Stackoverflow