谷歌应用程序脚本:是一个有范围的日期部分



我想确定日期介于哪个季节之间。日期在单元格中,与当前日期无关。

我已经走了这么远:

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")
}

我会在其他季节重复这一点。

我的预期是,1/13/2023通过(Utilities.formatDate(myDate, "GMT", 'MM/dd')评估为1/13,并随范围下降。

不会发生这种情况

提前谢谢。

下面是一个将今天的日期与季节进行比较的示例。

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

参考

  • 日期对象
  • 数组.findIndex((

一年中的季节:

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);
}

我从timeandate.com获得了这些数据,并将其放入Sheet0

3月1日,星期二月1日星期三月1日,星期四2月1日星期四
AB
夏季
FALL
冬季

最新更新