javascriptgoogle-sheetsgoogle-apps-script

Why can't I format my dates after they are returned from this function?


I have a Google sheet which takes dates and then uses this function.

function nextDueDate(date1, date2, date3, date4, date5, date6, done1, done2, done3, done4, done5, done6) {
  const today = new Date();
  const dates = [new Date(date1), new Date(date2), new Date(date3),new Date(date4), new Date(date5), new Date(date6)];
  var dones = [done1, done2, done3, done4, done5, done6];

  // Completes earlier tasks if subsequent tasks are completed
  var dones = dones.map((val,index) => { if(dones.lastIndexOf('x')>=index ) {return 'x'}});

  // Filter for dates that are not done
  const futureDates = dates.filter((date,index) => !dones[index]);

  // Find the earliest date from the filtered future dates
  const nextDueDate = futureDates.reduce((earliest, date) => {
    return date < earliest ? date : earliest;
  }, new Date('2999-12-31')); // initial date far in the future

  // If the nextDueDate year is still in the far future then all tasks are done (on no dates)
  return (nextDueDate.getFullYear() === 2999) ? 'DELETE' : nextDueDate.toLocaleDateString(); // Returns the next due date in a readable format
}

After the date is returned, the dates are formatted like this: 2024-06-26. But I want to be able to custom format them as 'Wed 26 June'. But when I try to change the date formatting it stays the same. I assume it's not returning as a normal date object. How do I get it to convert to a date type I can then re-format?


Solution

  • Changing the last line to this will return the date format you're looking for.

    return (nextDueDate.getFullYear() === 2999) ? 'DELETE' : Utilities.formatDate(nextDueDate, "GMT", "EEE dd MMM"); // Returns the next due date in a readable format