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

如何用JavaScript解析并比对weather.gov API的时段格式以获取当前气温?

解析weather.gov API时段格式并获取当前气温(JavaScript实现)

我来帮你搞定这个需求——weather.gov API的时段格式是标准的ISO 8601时间区间表示,咱们一步步拆解解析和匹配当前气温的逻辑:

1. 先搞懂时段格式的含义

你看到的2018-04-27T04:00:00+00:00/PT1H其实是两部分,用/分隔:

  • 前半段:2018-04-27T04:00:00+00:00 是时段起始时间,带UTC时区偏移(+00:00就是UTC时间)
  • 后半段:PT1H 是时段时长,遵循ISO 8601的时长规则:
    • P表示Period(周期),T表示Time(时间部分)
    • 后面的数字+单位:1H=1小时,30M=30分钟,2D=2天(如果涉及日期跨度的话)

2. 写一个解析时段的工具函数

咱们先写个函数,把这个时段字符串转换成起始和结束的Date对象,方便后续时间比对:

function parseWeatherTimeInterval(intervalStr) {
  const [startStr, durationStr] = intervalStr.split('/');
  
  // 解析起始时间为UTC时间对象
  const startTime = new Date(startStr);
  
  // 解析时长,计算结束时间
  const durationMatch = durationStr.match(/PT(\d+)([HM])/); // 匹配小时H或分钟M的常用情况
  if (!durationMatch) {
    throw new Error('无法识别的时段时长格式');
  }
  
  const [, value, unit] = durationMatch;
  const durationMs = unit === 'H' ? parseInt(value) * 3600000 : parseInt(value) * 60000;
  const endTime = new Date(startTime.getTime() + durationMs);
  
  return { startTime, endTime };
}

3. 匹配当前时间获取气温

拿到API返回的数据后,遍历气温数组(一般在properties.temperature.values路径下),检查当前时间是否落在某个时段的区间内,找到对应的气温值:

async function getCurrentTemperature(gridPointUrl) {
  try {
    // 注意:weather.gov API强制要求设置User-Agent头,否则会返回403
    const response = await fetch(gridPointUrl, {
      headers: {
        'User-Agent': '你的应用名称/1.0 (your-email@example.com)' // 替换成你的应用信息
      }
    });
    
    if (!response.ok) {
      throw new Error(`API请求失败:${response.status} ${response.statusText}`);
    }
    
    const data = await response.json();
    const temperatureEntries = data.properties.temperature.values;
    const nowUTC = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate(), new Date().getUTCHours(), new Date().getUTCMinutes()));
    
    // 遍历所有气温时段,找到当前UTC时间所在的区间
    for (const entry of temperatureEntries) {
      const { startTime, endTime } = parseWeatherTimeInterval(entry.validTime);
      
      if (nowUTC >= startTime && nowUTC < endTime) {
        return {
          tempValue: entry.value,
          unit: data.properties.temperature.unitCode, // 通常是°F或°C
          validPeriod: entry.validTime
        };
      }
    }
    
    // 极端情况:未找到匹配时段(API时段一般是连续的,大概率不会触发)
    return null;
  } catch (error) {
    console.error('获取当前气温出错:', error);
    throw error;
  }
}

// 调用示例
getCurrentTemperature('https://api.weather.gov/gridpoints/EAX/41,43')
  .then(result => {
    if (result) {
      console.log(`当前气温:${result.tempValue} ${result.unit}`);
    } else {
      console.log('未找到匹配的气温数据');
    }
  })
  .catch(err => console.error(err));

关键注意事项

  • 必须设置User-Agent:weather.gov API要求所有请求携带该头,注明应用名称和联系方式,否则会被拒绝访问
  • 时区对齐:API返回的所有时间都是UTC,所以一定要用UTC时间进行比对,避免本地时区偏移导致匹配错误
  • 可扩展时长解析:如果API返回包含天级别的时段(比如PT2D),可以扩展parseWeatherTimeInterval函数,增加对D单位的处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:06:58