Matarishvan
Matarishvan

Reputation: 2432

javascript - date should be from 1st Nov of current year to 10th Feb of next year

i'm putting some condition that date should be from 1st Nov of current year to 10th Feb of next year

This is what i have tried

if((date.getDate() >= 1 && date.getMonth() === 11 && date.getFullYear()) && (date.getDate() <= 10 && date.getMonth() === 2 && date.getFullYear + 1)){
   condition satisfied
}

Obviously which is not working. What is the proper way in javascript to put this condition.

Upvotes: 0

Views: 375

Answers (3)

Arun
Arun

Reputation: 684

You can easily use Moment.js

let checkDifferenceDate = moment() >= moment("12/01/"+moment().year()) && moment() <= moment("01/31/"+moment().add(1,'year').year())
if(checkDifferenceDate){
    //You logic here !
}

Upvotes: 0

RobG
RobG

Reputation: 147413

The code doesn't work because when comparing dates, you have to compare the entire date, not just the parts. You can can get the current year from a Date instance, then use it to create the limit dates to compare it to, e.g.

function testDate(date) {
  var year = new Date().getFullYear();
  return date >= new Date(year, 10, 1) &&       // 1 Nov current year
         date <= new Date(year + 1, 1, 11) - 1; // 10 Feb next year at 23:59:59.999
}

// Some tests
[new Date(2018,9,31),  // 31 Oct 2018
 new Date(2018,10,1),  //  1 Nov 2018
 new Date(2019,1,10),  // 10 Feb 2018
 new Date(2019,1,11),  // 11 Feb 2018
 new Date()]           // Current date
 .forEach(function(date) {
   console.log(date.toLocaleString(undefined, {day: '2-digit',
     month:'short', year:'numeric'}) + ': ' + testDate(date));
 });

All of the above dates are treated as local for the host.

Upvotes: 0

avolkmann
avolkmann

Reputation: 3105

Here is a solution that works:

function check(date) {
  currentYear = new Date().getFullYear()
  return  date > new Date(currentYear + '-11-01') && date < new Date(currentYear + 1 + '-02-10')
}

console.log(check(new Date())); // currently false
console.log(check(new Date('2018-12-01'))); // true
console.log(check(new Date('2019-01-31'))); // true

Use it as follows:

if(check(date)) {
    ...
}

Upvotes: 1

Related Questions