You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets自定义SolarTimes函数获取晨昏时间报错排查

Google Apps Script 晨昏时间自定义函数修复方案

你的代码存在3个会直接触发报错/逻辑失效的问题:

  • 变量名前后不一致:前期定义的变量为civil_dawn、civil_dusk、nautical_dawn、nautical_dusk,分支返回时写的是缺失下划线的civildawn、civildusk、nauticaldawn、nauticaldusk,属于未定义变量,运行时会直接抛出引用错误。
  • 比较运算符误用:判断Civil_Dawn类型的分支中,错误使用赋值运算符=代替相等判断运算符==,会直接修改传入的type参数值,导致后续分支判断完全失效。
  • 冗余语法:if判断逻辑外层包裹了一层无意义的花括号,虽不会直接触发报错,但容易混淆代码块边界,提升后续维护的出错概率。

除此之外原代码还有两个影响实际使用的缺陷:一是接口默认返回UTC时区的12小时制时间字符串,直接在表格中使用会出现时区偏差;二是没有做接口异常判断,参数传错时只会抛出模糊的运行错误,无法快速定位问题。

修复后可直接复用的完整代码

function SolarTimes(lat, long, date, type) {
  // 新增formatted=0参数,返回标准ISO格式时间方便做时区转换
  const requestUrl = `https://api.sunrise-sunset.org/json?lat=${lat}&lng=${long}&date=${date}&formatted=0`;
  const response = UrlFetchApp.fetch(requestUrl);
  const resData = JSON.parse(response.getContentText());

  // 接口请求异常时直接返回明确提示
  if (resData.status !== "OK") {
    throw new Error("参数错误,请检查经纬度、日期格式是否合法");
  }

  // 用键值对映射替代多分支if判断,后续新增晨昏类型直接加键值对即可
  const timeMap = {
    "Sunrise": resData.results.sunrise,
    "Sunset": resData.results.sunset,
    "Civil_Dawn": resData.results.civil_twilight_begin,
    "Civil_Dusk": resData.results.civil_twilight_end,
    "Nautical_Dawn": resData.results.nautical_twilight_begin,
    "Nautical_Dusk": resData.results.nautical_twilight_end,
    "Day_Length": resData.results.day_length
  };

  // 传入的时间类型不支持时返回提示
  if (!timeMap.hasOwnProperty(type)) {
    return "无效时间类型";
  }

  // 日长做格式化处理,其余时间转成本地时区Date对象供表格识别
  if (type === "Day_Length") {
    const totalSec = timeMap[type];
    const hour = Math.floor(totalSec / 3600);
    const min = Math.floor((totalSec % 3600) / 60);
    return `${hour}小时${min}分钟`;
  } else {
    return new Date(timeMap[type]);
  }
}

使用说明

  • 直接在单元格内按=SolarTimes(纬度所在单元格, 经度所在单元格, 日期所在单元格, "时间类型")格式调用即可,引用单元格内容变更时函数会自动重算。
  • 时间类型参数支持传入的值为:Sunrise、Sunset、Civil_Dawn、Civil_Dusk、Nautical_Dawn、Nautical_Dusk、Day_Length。
  • 日期参数请直接引用表格内设置为日期格式的单元格,不要传入手动拼接的文本字符串,避免接口解析失败。
  • 若需要每日自动更新数据,可在表格设置中将自定义函数的重算规则调整为「打开时和每小时」,无需额外编写定时触发代码。

内容的提问来源于stack exchange,提问作者Pvs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 08:06:23