dist
dist

Reputation: 45

Date validation JS

I have to make a date validation in 'DD/MM/YYYY' format. The date must:

It works fine, but it takes the current day as an invalid date. I tried a lot of things, but I can't figure it out why. Maybe the problem is in if construction...

let daaa = moment(new Date()).date();
let daaad = moment(new Date()).date();
alert(moment(daaad).isSame(daaa));

also try new Date().getTime() and getDate()

const selectedDate = new Date(value.split('/').reverse().join('-'));
let today = new Date(Date.now());
let plusSixMonths = new Date(Date.now());
plusSixMonths.setMonth(plusSixMonths.getMonth() + 6);
if (selectedDate >= today && plusSixMonths > selectedDate) return true;

I expected to catch also the current date in valid dates.

Upvotes: 1

Views: 75

Answers (1)

phuzi
phuzi

Reputation: 13059

The problem is caused by Date.now(), it includes the current time. So if you're checking 28/10/2019 then 2019-10-28T00:00:00 is almost certainly before today's date with a time component:

(selectedDate >= today && plusSixMonths > selectedDate)

becomes

(2019-10-28T00:00:00 >= 2019-10-28T11:02:32 && 2020-04-28T11:02:32 > 2019-10-28T00:00:00)

Which is going to be false.

You'll need to remove the time components from today (new Date() also gets the current time as a date object)

let today = new Date();
// set hours, minutes, seconds and milliseconds to zero i.e. 12am
today.setHours(0, 0, 0, 0);

Then you should be able to make the comparison as you expected.

Update Thanks to RobG for pointing out that setHours can also set minutes, seconds and milliseconds.

Upvotes: 1

Related Questions