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

如何在AngularJS中为API返回的UTC日出日落时间加2小时?

解决AngularJS中日出日落UTC时间转本地时间(加2小时)的问题

你需要把API返回的UTC日出日落时间加上2小时,转换成目标本地时间格式对吧?这里有个实用的实现方案,我们可以写个辅助函数来处理时间的加减和格式化:

首先,创建一个专门处理时间加指定小时数的函数,它能接收原始的时间字符串(比如1:01:19 AM),返回调整后的格式化时间:

function addHoursToTime(timeStr, hoursToAdd) {
  // 用正则拆分时间的时、分、秒和AM/PM标识
  const timeParts = timeStr.match(/(\d+):(\d+):(\d+) (AM|PM)/);
  const [, hours, minutes, seconds, period] = timeParts;
  
  // 基于UTC日期创建Date对象,避免本地时区干扰
  let date = new Date(Date.UTC(2000, 0, 1));
  // 处理12小时制转24小时制
  if (period === 'AM') {
    date.setUTCHours(hours === '12' ? 0 : parseInt(hours));
  } else {
    date.setUTCHours(hours === '12' ? 12 : parseInt(hours) + 12);
  }
  date.setUTCMinutes(parseInt(minutes));
  date.setUTCSeconds(parseInt(seconds));
  
  // 添加指定小时数
  date.setUTCHours(date.getUTCHours() + hoursToAdd);
  
  // 格式化回12小时制的目标格式
  let formattedHours = date.getUTCHours();
  const newPeriod = formattedHours >= 12 ? 'PM' : 'AM';
  formattedHours = formattedHours % 12;
  formattedHours = formattedHours === 0 ? 12 : formattedHours;
  
  const formattedMinutes = String(date.getUTCMinutes()).padStart(2, '0');
  const formattedSeconds = String(date.getUTCSeconds()).padStart(2, '0');
  
  return `${formattedHours}:${formattedMinutes}:${formattedSeconds} ${newPeriod}`;
}

接下来,修改你的AngularJS控制器代码,在获取API响应后调用这个函数处理时间:

$http.get("https://api.sunrise-sunset.org/json?lat=63.8258&lng=20.2630&date=today", {})
  .then(function(response){
    const originalSunrise = response.data.results.sunrise;
    const originalSunset = response.data.results.sunset;
    
    // 给两个时间都加上2小时
    const adjustedSunrise = addHoursToTime(originalSunrise, 2);
    const adjustedSunset = addHoursToTime(originalSunset, 2);
    
    console.log("原日出时间: " + originalSunrise);
    console.log("调整后日出时间: " + adjustedSunrise);
    console.log("原日落时间: " + originalSunset);
    console.log("调整后日落时间: " + adjustedSunset);
    
    $scope.string = ("sunset: " + adjustedSunset + "\n" + "sunrise: " + adjustedSunrise);
  });

$scope.post_tweet = function(){
  $http.post('index.php',{
    'string':$scope.string
  }).then(function(response){
    // 清空表单提示
    $scope.msg = true;
    $timeout(function(){$scope.msg = false;}, 1000);
    console.log("in " + response.data);
  });
};

逻辑说明:

  • addHoursToTime函数先拆分原始时间的各个部分,用UTC基准的Date对象处理时间计算,避免本地时区的自动转换干扰。
  • 调整小时数后,再把时间重新格式回你需要的HH:MM:SS AM/PM格式,保证输出和原始格式一致。
  • 在API响应处理中,我们用这个函数分别处理日出和日落时间,再拼接成最终要发布的字符串。

这样修改后,你的输出就会变成期望的"sunset: 10:10:09 PM sunrise: 3:01:19 AM"格式啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:46:20