Home > Software engineering >  Google Apps Script: Is a date part with a range
Google Apps Script: Is a date part with a range

Time:09-13

I would like to determine what season a date falls between. The date is in a cell and is not related to the current date.

I have gotten this far:

var myDate=myForm.getRange("C4").getValue();

if (Utilities.formatDate(myDate, "GMT", 'MM/dd')>'12/21' && Utilities.formatDate(myDate, "GMT", 'MM/dd')<'3/20'){
  ui.alert("Winter")
}

I would repeat this obviously for other seasons.

My expectation is that 1/13/2023 evaluates to 1/13 by (Utilities.formatDate(myDate, "GMT", 'MM/dd') and falls with the range.

That is not happening

Thanks in advance.

CodePudding user response:

Here is an example of comparing today's date with the season.

function getSeason() {
  try {
    // per Farmers Almanac
    let season = ["Winter","Spring","Summer","Fall"];
    let seasons = [["12/21/2021","3/20/2022","6/21/2022","9/22/2022","12/21/2022","3/20/2023"],
                   ["12/21/2022","3/20/2023","6/21/2023","9/23/2023","12/21/2023","3/20/2024"],
                   ["12/21/2023","3/19/2024","6/20/2024","9/22/2024","12/21/2024","3/20/2025"],
                   ["12/21/2024","3/20/2025","6/20/2025","9/22/2025","12/21/2025","3/20/2026"],
                   ["12/21/2025","3/20/2026","6/21/2026","9/22/2026","12/21/2026","3/20/2027"]];
    let today = new Date();
    let year = today.getFullYear()-2022;
    today = new Date(today.getFullYear(),today.getMonth(),today.getDate());
    let found = seasons[year].findIndex( (date,index) => {
        return today >= new Date(date) && today < new Date(seasons[year][index 1]);
      }
    );
    console.log(today);
    console.log(season[found])
  }
  catch(err) {
    console.log(err);
  }
}

12:20:50 PM Notice  Execution started
12:20:50 PM Info    Mon Sep 12 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
12:20:50 PM Info    Summer
12:20:50 PM Notice  Execution completed

Reference

CodePudding user response:

Season of the year:

function seasonOfTheYear(date) {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const ds = sh.getDataRange().getValues();
  const sObj = { pA: [] };
  ds.forEach(s => {
    sObj[new Date(s[1]).valueOf()] = { start: new Date(s[1]), season: s[0] };
    sObj.pA.push(new Date(s[1]).valueOf());
  });
  let dv = new Date(date).valueOf();
  let ssn = sObj.pA.reduce((a, c, i) => {
    if (dv >= c && dv < sObj.pA[(i   1) % sObj.pA.length]) {
      a["season"] = sObj[c].season;
    }
    return a;
  }, {season:''}).season;
  Logger.log(ssn);
}

I got this data from timeandate.com and put it into Sheet0

A B
SPRING Tuesday, March 1
SUMMER Wednesday, June 1
FALL Thursday, September 1
WINTER Thursday, December 1
  • Related