-1

I need to validate that a date is in this format (yyyy-mm)
and make sure its before todays date My question is why when I am using this constructor I get one month forward?

new Date(year, month, day, hours, minutes, seconds, milliseconds)

And is this the best approach for such a task? Thank you!

function testDate(dateString){
  dateString = dateString.trim();
  var regEx = /^\d{4}-([0][1-9]|[1][0-2])$/ ;
  if(dateString.match(regEx) !== null){

      var spArr = dateString.split('-');
      var year = parseInt(spArr[0], 10); 
      var month =parseInt(spArr[1], 10); 
      
      var currentDate = new Date();
      inputDate = new Date(year, month, 1, 12, 30, 0, 0);
      alert('year: ' + year + ' month: ' + month);
      alert(inputDate);

      if(inputDate > currentDate){
          alert('Input date ['+dateString+'] is greater than the current date!');
      }
      alert('all ok!');

  }else{
      alert('Input date ['+dateString+'] is of invalid format, correct format: yyyy-MM example: 1975-09');
  }
}

testDate('2014-04                  ');
testDate('14-04');
testDate('2014-4');
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159

1 Answers1

2

No need to reinvent the wheel. The Date constructor already handles that for you.

const testDate = str => {
  if (/^\d{4}-([0][1-9]|[1][0-2])$/.test(str)===null) return false;
  let now = new Date();
  try {
    return new Date(str)<new Date();
  } catch(err) {
    console.log(err);
    return false;
  }
}

console.log(testDate('2014-04                  '));
console.log(testDate('14-04'));
console.log(testDate('2014-04'));
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84