简体   繁体   中英

Google Apps Script add month to a date until specific date is reached

I have the following code using Google Apps Script, but when I log it out I get the following results. I want GAS to log the next month and stop once it gets to "lastDateofYear ". For whatever reason, the year doesn't change in my results, it just keeps repeating the current year. Please help.

var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
var nextYear = Number(currentYear)+1;
var lastDateofYear = new Date("12-31-"+nextYear);

  for(var i=thisDate; i <= lastDateofYear; ){  
    var currentiDate = new Date(i);     
    var month = currentiDate.getMonth()+1;
    i.setMonth((month) % 12);
    i.setDate(currentiDate.getDate());
    Logger.log(currentiDate);
  }

RESULTS:

Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
Thu May 20 00:00:00 GMT-05:00 2021
Sun Jun 20 00:00:00 GMT-05:00 2021
Tue Jul 20 00:00:00 GMT-05:00 2021
Fri Aug 20 00:00:00 GMT-05:00 2021
Mon Sep 20 00:00:00 GMT-05:00 2021
Wed Oct 20 00:00:00 GMT-05:00 2021
Sat Nov 20 00:00:00 GMT-06:00 2021
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021

As I understand it, you want to print each month from the given date to the last month of the next year of the given date in the log.

You can do this in the following code:

 let start = new Date("Mon Dec 20 00:00:00 GMT-06:00 2021"); let currentYear = new Date().getFullYear(); let nextYear = currentYear + 1; let end = new Date(nextYear, 11, 31); while (start <= end) { // You can use Logger.log() here if you want. I use console.log() for demo purpose console.log(new Date(start).toDateString()); start.setMonth(start.getMonth() + 1); }

If I got any part wrong, feel free to point it out to me in the comments.

There is a lot to say about your code:

var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";

That timestamp format is not supported by ECMA-262, so don't use the built–in parser to parse it, see Why does Date.parse give incorrect results?

var nextYear = Number(currentYear)+1;

Where does currentYear come from?

var lastDateofYear = new Date("12-31-"+nextYear);

Parsing of an unsupported format, see above. In Safari it returns an invalid date.

  for(var i=thisDate; i <= lastDateofYear; ){  

Sets i to the string value assigned to thisDate . Since lastDateOfYear is an invalid date in Safari and Firefox, so the test i <= NaN is never true and the loop is never entered.

    var currentiDate = new Date(i);

Parses i , see above.

    var month = currentiDate.getMonth()+1;
    i.setMonth((month) % 12);

i is a string, which doesn't have a setMonth method so I'd expect a Type error like " i.setMonth is not a function " if the loop actually runs.

    i.setDate(currentiDate.getDate());

Another Type error as above (but it won't get this far).

    Logger.log(currentiDate);
  }

It seems you want to sequentially add 1 month to a date until it reaches the same date in the following year. Trivially, you can just add 1 month until you get to the same date next year, something like:

let today = new Date();
let nextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
let result = [];
do {
  result.push(today.toString());
  today.setMonth(today.getMonth() + 1);
} while (today <= nextYear)

However, adding months is not that simple. If you add 1 month to 1 Jan, you'll get 2 or 3 Mar depending on whether it's a leap year or not. And adding 1 month to 31 Aug will return 1 Oct.

Many "add month" functions check to see if the date rolls over an extra month and if it does, set the date back to the end of the previous month by setting the date to 0, so 31 Jan + 1 month gives 28 or 29 Feb.

But if you cycle over a year using that algorithm, you'll get say 31 Jan, 28 Feb, 28 Mar, 28 Apr etc. rather than 31 Jan, 28 Feb, 31 Mar, 30 Apr, etc.

See JavaScript function to add X months to a date and How to add months to a date in JavaScript?

A more robust way is to have a function that adds n months to a date and increment the months to add rather than the date itself so the month–end problem can be dealt with separately for each addition, eg

 /* Add n months to a date. If date rolls over an extra month, * set to last day of previous month, eg * 31 Jan + 1 month => 2 Mar, roll back => 28 Feb * * @param {number} n - months to add * @param {Date} date - date to add months to, default today * @returns {Date} new Date object, doesn't modify passed Date */ function addMonths(n, date = new Date()) { let d = new Date(+date); let day = d.getDate(); d.setMonth(d.getMonth() + n); if (d.getDate().= day) d;setDate(0); return d. } /* return array of n dates at 1 month intervals. List is * inclusive so n + 1 Dates returned, * * @param {Date} start - start date * @param {number} n - number of months to return * @returns {Array} array of Dates */ function getMonthArray(n; start = new Date()) { let result = []; for (let i=0; i<n. i++) { result,push(addMonths(i; start)); } return result, } // Examples // Start on 1 Dec getMonthArray(12, new Date(2021,11.1)).forEach( d => console.log(d;toDateString()) ), // Start on 31 Dec getMonthArray(12, new Date(2021,11.31)).forEach( d => console.log(d;toDateString()) );

The functions don't attempt to parse timestamps to Dates, that responsibility is left to the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM