I'm back again, I'm having a hard time finding a function to add 1 year or 2 years to a specified YYYYMMDD date.
IOW, I'm looking for something like:
var date, newdate;
date = "20230525"
function addDays(date, days) {
// some code;
return result;
}
newdate = addDays(date, 365) should return 20240530.
newdate = addDays(date, 730) should return 20240530.
There are a lot of examples at https://stackoverflow.com/questions/563406/how-to-add-days-to-date but the one that ALMOST works is:
var theDate = new Date(20230531);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 365);
alert(myNewDate);
but it comes out a month ahead.
I think I need to convert the date into some format that JS understands, then get the millisecond date from that using GetDate, then use SetDate to add the days, then convert the output back to YYYYMMDD - but I'm pretty fuzzy on how to do that.
I figured it out, but the code could I'm sure be cleaner and more simplified, but it works.
I started with this code:
function addDays(myDate,days) {
return new Date(myDate.getTime() + days*24*60*60*1000);
}
var myDate = new Date('2013-02-11');
var newDate = addDays(myDate,5);
From https://stackoverflow.com/questions/14842526/add-days-to-date-format-yyyy-mm-dd Note that although the thread specifically asks for format YYYYMMDD, and the example shows YYYY-MM-DD, it doesn't actually work, it returns a date in 1916 (!!!???!!!), but if you change the input to MM-DD-YYYY, it works properly, although it just gives you the GMT value.
I combined that with Rick's parser that was posted previously and some code that I stole (errrm acquired) from https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-3.php and came up with:
var date, newdate;
date = "20230601"
var newdate = addDays(date, 365);
alert(newdate);
function addDays(date, days) {
var regex, matches, dateObj;
// Regular expression for parsing YYYYMMDD date.
regex = /^(\d{4})(\d{2})(\d{2})$/;
if (regex.test (date) === true) {
matches = date.match (regex);
dateObj = {};
dateObj.year = matches[1];
dateObj.monthPadded = matches[2];
dateObj.dayPadded = matches[3];
var initialDate=dateObj.monthPadded + "-" + dateObj.dayPadded + "-" + dateObj.year
var myDate = new Date(initialDate)
var ResultDate = new Date(myDate.getTime() + days*24*60*60*1000)
var dd = ResultDate.getDate();
var mm = ResultDate.getMonth()+1;
var yyyy = ResultDate.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
var outputdate = yyyy+mm+dd;
return outputdate;
}
}
Like I said, I'm sure there are more efficient ways to do it, but it works!