Check if one date is between two dates
Asked Answered
R

15

124

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?

Reprisal answered 18/4, 2013 at 10:23 Comment(1)
Daniel, you need to update the corrrect answer. The answer with more votes doesn't check for dates only for monthsBurget
O
142

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)
Ormond answered 18/4, 2013 at 10:36 Comment(4)
+1 for correctly parsing the date string and not leaving it up to an implementation dependent parser.Fourierism
Consider db conventions, first date should be inclusive. e.g. check >= from && check < toJohansen
@Ormond check :02/23/2018 from:11/20/2018 to:12/31/2018 it returns true.Quint
@chudasamachirag: The question was about parsing dd/mm/yyyy format. These dates are in mm/dd/yyyy formatOrmond
G
81

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");
Georama answered 18/4, 2013 at 10:26 Comment(3)
NaN neither has a GetTime nor a getTime method?Whereupon
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 :)Piety
@SayanSamanta: Your solution is simple & it works. Thanks. Note for others: Time is not checked here.Inquisitor
D
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;
}
Digression answered 18/4, 2013 at 10:46 Comment(5)
@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 himDigression
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)Whereupon
What if I wanted to check if now falls under 7:00am to 9:00pmSherronsherry
dateCheck("20/01/2015","22/01/2015","21/02/2015") this case doesnt workFlog
@BhavinRana This case does not work because you use dd/mm/yyyy - correct would be mm/dd/yyyySternmost
B
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);
Burget answered 5/5, 2017 at 21:55 Comment(0)
J
11

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

Jubilee answered 24/12, 2019 at 13:59 Comment(2)
this code does not work in safariLax
@Lax just tested in latest Safari 15.6 and it's working. Here's a test link - codepen.io/andrew_mykhalchuk/pen/gOejKpWJubilee
C
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);
}
Clotilda answered 11/8, 2019 at 19:15 Comment(0)
L
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();
};
Laid answered 26/9, 2018 at 1:7 Comment(0)
S
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);
        }
})
Scintillator answered 9/2, 2019 at 22:39 Comment(0)
A
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
    }
Alburnum answered 23/10, 2020 at 5:38 Comment(0)
B
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/

Bieber answered 19/10, 2017 at 9:35 Comment(0)
A
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}

}
Ampereturn answered 13/9, 2022 at 15:35 Comment(2)
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!Dilapidation
I'll do so. @TobiasSchäfer But what's not working properly ?Ampereturn
U
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)
Ureide answered 3/4, 2023 at 19:8 Comment(0)
P
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);
Physiography answered 1/11, 2023 at 10:30 Comment(0)
S
-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

Supporter answered 9/5, 2014 at 11:54 Comment(0)
C
-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');
}
Collard answered 9/6, 2022 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.