Nandha Kumar
Nandha Kumar

Reputation: 101

how can i compare date strings?

i need to check whether the date is between minDate and maxDate. but when i try to compare with minDate, i should get valid as false but am getting true..

            let minDate = "27-05-2019";
        let maxDate = "27-05-2019";
        let date = "13-02-2018";
        var valid;

        if(new Date(date.replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3")).toDateString() >= new Date(minDate.replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3")).toDateString()){
            valid = true;
            } else {
            valid = false;
            }
            
            console.log(valid);

thanks in advance

Upvotes: 2

Views: 87

Answers (4)

Jared Smith
Jared Smith

Reputation: 21926

Plain JS solution with a couple of helper functions:

const splitMyDateString = str => {
  const [day, mon, yr] = str.split('-').map(Number);
  return [yr, mon, day];
};

const makeDate = ([yr, mon, day]) => {
  return new Date(yr, mon - 1, day);
};

let minDate = makeDate(splitMyDateString("27-05-2019"));
let maxDate = makeDate(splitMyDateString("27-05-2019"));
let date = makeDate(splitMyDateString("13-02-2018"));
let valid = (date >= minDate) && (date <= maxDate);

Note that the Date constructor is not guaranteed to accept strings except in the ISO 8601 format. So here we're passing integers instead. Note also we have to subtract 1 from the month because JS months are 0-11, not 1-12.

Upvotes: 2

Derik Nel
Derik Nel

Reputation: 423

You can use the JavaScript Date method: https://www.w3schools.com/js/js_date_methods.asp

let minDate = new Date("2018-01-13"),
    maxDate = new Date("2018-03-13"),
    date = new Date("2018-02-13"),
    valid = false;

if (date.getTime() >= minDate.getTime() && date.getTime() <= maxDate.getTime()) {
    valid = true;
}

Upvotes: 1

Luke Walker
Luke Walker

Reputation: 501

Use moment.js

isBetween - link

moment().isBetween(moment-like, moment-like);

Example

let minDate = "27-05-2019";
let maxDate = "27-05-2019";
let date = "13-02-2018";

moment(date).isBetween(moment(minDate), moment(maxDate));

Upvotes: 2

Lucas Ferreira
Lucas Ferreira

Reputation: 888

When you use the toDateString() method, you are converting your Date object to a string, thus you are only comparing two strings in your if.

Remove this method call and it should work.

let minDate = "27-05-2019";
let maxDate = "27-05-2019";
let date = "13-02-2018";
var valid;

if (new Date(date.replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3")) >= new Date(minDate.replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))) {
  valid = true;
} else {
  valid = false;
}

console.log(valid);

Upvotes: 1

Related Questions