0

I have the following script to check if a date is valid:

var text = '2/31/2013'; 
var comp = text.split('/'); 
var m = parseInt(comp[0], 10); 
var d = parseInt(comp[1], 10); 
var y = parseInt(comp[2], 10); 
var date = new Date(y,m-1,d); 
if(date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
    console.log('Valid date'); 
}
else {
    console.log('Invalid date');
    var NextValidDate = new Date(y,m-1,d+1);
    console.log(NextValidDate);    
}

I would like to jump now to the next correct date. In the sample case is this the 01. March 2012.

But how to get it? NextValidDate gives not always a correct date.

hamburger
  • 1,339
  • 4
  • 20
  • 41
  • Increase the days by one? – Felix Kling Jun 21 '13 at 20:27
  • I do not wont to add a number of days. Here I do not know them. The days to add are different on februar the 29, 30 ,31. And it is not possible to add days on unvalid dates. – hamburger Jun 21 '13 at 20:31
  • Voted to reopen because it is, after all, not a duplicate. Though I think the question could be phrased better, i.e. provide an explanation of the context. – Felix Kling Jun 22 '13 at 11:29

3 Answers3

1
var originalDate = new Date(2013, 2, 31);
var nextDate = new Date(originalDate.getFullYear(), originalDate.getMonth(), originalDate.getDay() + 1);
LaurentG
  • 11,128
  • 9
  • 51
  • 66
1

According to your logic, if a date does not exist (which can only happen if the month has less days than provided as input), then the first day of the next month is the next "correct" date.

In that case you create the next valid date by adding one to the month and set the days to 1:

var NextValidDate = new Date(y, (m-1) + 1, 1);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Part of the problem is that most browsers will interpret new Date(2013, 1, 31) as March 4, 2013 (or 2/28/2013 + 3 days). Thus, while:

date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d

returns false, the parsed date is still a technically valid date. I suspect you simply want to advance to the next month in the event that m/d/y entered is not the same m/d/y that is parsed. If that's the case, make your nextValidDate the first of the following month:

var text = '2/31/2013',
    comp = text.split('/'),
    m = parseInt(comp[0], 10),
    d = parseInt(comp[1], 10),
    y = parseInt(comp[2], 10),
    date = new Date(y, m - 1, d),
    nextValidDate;
if (date.getFullYear() === y && date.getMonth() + 1 === m && date.getDate() === d) {
    console.log('Valid date'); 
} else {
    console.log('Invalid date');
    nextValidDate = new Date(y, m, 1);
    console.log('Next valid date: ' + nextValidDate);
}
pete
  • 24,141
  • 4
  • 37
  • 51
  • What can I do if I come backwards from the first of march to februar or from 1. december to 30. november? Do I have to ckeck it for each month separately? – hamburger Jun 21 '13 at 21:20