125

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?

1
  • Daniel, you need to update the corrrect answer. The answer with more votes doesn't check for dates only for months Commented Aug 24, 2018 at 6:26

16 Answers 16

145

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)
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for correctly parsing the date string and not leaving it up to an implementation dependent parser.
Consider db conventions, first date should be inclusive. e.g. check >= from && check < to
@Diode check :02/23/2018 from:11/20/2018 to:12/31/2018 it returns true.
@chudasamachirag: The question was about parsing dd/mm/yyyy format. These dates are in mm/dd/yyyy format
84

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");

3 Comments

NaN neither has a GetTime nor a getTime method?
It will perfectly be working when date format is like - 02/05/2013 but when date is in iso format(date+time) like - 2019-09-12T13:02:14.291Z then use the setHours method before compare dates, Ex - let compareDate = new Date('checkDate').setHours(0, 0, 0, 0); let startDate = new Date('startDate').setHours(0, 0, 0, 0); let endDate = new Date('endDate').setHours(0, 0, 0, 0); console.log(compareDate <= endDate && compareDate >= startDate); Hope it will help others :)
@SayanSamanta: Your solution is simple & it works. Thanks. Note for others: Time is not checked here.
25

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;
}

5 Comments

@Bergi: If the Date is NAN then this function return False So the Date you check Or Pass is Not Availed or In Valid and this is the HELL difference between the code of mine and him
But the OP's if-condition does that as well? And the question was about the date being NaN in the first place (which it is not in all browsers)
What if I wanted to check if now falls under 7:00am to 9:00pm
dateCheck("20/01/2015","22/01/2015","21/02/2015") this case doesnt work
@BhavinRana This case does not work because you use dd/mm/yyyy - correct would be mm/dd/yyyy
12

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);

2 Comments

this code does not work in safari
@Ulugbek just tested in latest Safari 15.6 and it's working. Here's a test link - codepen.io/andrew_mykhalchuk/pen/gOejKpW
11

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);

Comments

3

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);
}

Comments

1

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();
};

Comments

1

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);
        }
})

Comments

1

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
    }

Comments

0

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/

Comments

0

This may feel a bit more intuitive. The parameter is just a valid date string. This function returns true if the date passed as argument is in the current week, or false if not.

function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()

// create a date instance with the function parameter 
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)

// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){ 
  console.log("invalid date format")
  return false}

// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]

// get Monday date by substracting the day index (number) in the week from the day value (count) 
//in the month (like october 15th - 5 (-> saturday index)) and +1 because 
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1

// get Saturday date
const sunday = monday + 6

// Start verification
if (yearR !== WEEK.getFullYear())  { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}

}

2 Comments

Hi @Wilfried. could you please format your code to explain the solution you are providing. Currently the answer dooes not look working properly. Thank you!
I'll do so. @TobiasSchäfer But what's not working properly ?
0

This will work in all cases.

var curr = new Date("12/01/2023"); // get current date
console.log("curr.getDate()",curr.getDate());
console.log("curr.getDay()",curr.getDay());
var first = curr.getDate() - (curr.getDay()-1); //-1to make monday first day.
console.log(first)
var firstday = new Date(curr.setDate(first)); // 
console.log("first date",firstday)
var firstDay_no=firstday.getDate();
console.log("firstDay_no",firstDay_no)
var last = firstDay_no+ 6; // last day is the first day no + 6
console.log("last",last)
var lastday = new Date(curr.setDate(last)); //

console.log("last date",lastday)

Comments

0
const dateFrom = new Date(new Date().getFullYear(), 11, 1); 
const dateTo = new Date(new Date().getFullYear() + 1, 0, 6);

const dateCheck = new Date("02/07/2013");

const isBetween = dateCheck >= dateFrom && dateCheck <= dateTo;

console.log('is date in range?', isBetween);

Comments

0

Check if date is available in the range within plain time. below are examples: if today now is 24-09-2024 and time is 11:00 AM, then below values are:

  • 0-1 > between 24-09-2024 00:00:00 and current time.
  • 1-2 > between 23-09-2024 00:00:00 and 24-09-2024 00:00:00
  • 2-3 > between 22-09-2024 00:00:00 and 23-09-2024 00:00:00
const start = this.goBackByDays(DaysAgoFrom);
const end = this.goBackByDays(daysAgoTo);
const dateToCheck = Date.parse(this.responseData[0].sent);
this.presentOrNot = DaysAgoFrom
  ? dateToCheck >= start && dateToCheck <= end
  : dateToCheck <= end;

    goBackByDays(days: number) {
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - Math.abs(days ? days - 1 : 0));
      days != 0 ? startDate.setHours(0, 0, 0, 0) : null;
      console.log(startDate.toString());
      return Date.parse(startDate.toString());
    }

https://stackblitz.com/edit/angular-v7b4kd?file=src%2Fapp%2Fapp.component.ts

Comments

-1

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

Comments

-1

This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.

const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';

if (
  DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
  DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
  console.log('within range');
} else {
  console.log('not in range');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.