我正在使用Elian Ebbing's中的here数据验证代码,验证之后,我想输入输入的日期,并在X个月后返回一个新日期。例如,如果我输入06/09/2019,那么我希望代码返回6个月后的正确新日期,即12/6/2019。
有人可以帮助指导我完成此过程吗?我一直在尝试不同的方法来重用原始代码以获得所需的结果,但是自7月2日以来,我一直在这样做,并得出结论,我无法自己解决这个问题。我完全迷住了。
最后,我最深深的歉意是,我不只是评论埃宾先生代码的原始线程并寻求帮助,但不幸的是,我没有足够的声誉来做到这一点。
答案 0 :(得分:1)
如果不确定使用某些库(moment.js)是否很好。如果您想找到已经发现的东西,请准备撞碰头。
// Elian Ebbing validator
function isValidDate(dateString) {
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
// if you want to change date format
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1), // monts start form 0 so for result 06/01/2019
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [month, day, year].join('/');
}
// increment Date with count of months
function incrementDate(date, counter = 0) {
if (isValidDate(start_date_value)) {
var newDate = new Date(date);
newDate.setMonth(newDate.getMonth() + counter);
console.log(formatDate(newDate));
}
}
var start_date_value = "01/01/2019";
incrementDate(start_date_value, 5) ; // 06/01/2019