simpleWeather 和 moment.js - 德国的 js-geolocation 日期无效

simpleWeather and moment.js - invalid date with js-geolocation in Germany

嘿嘿=)

我想为我的网站创建一个天气插件。所以我选择 simpleWeather 插件。

simpleWeather 插件使用 moment.js 库获取最后更新时间。但是插件本身不提供语言选项。

我的标准位置是"Kiel, Germany"。

但它不起作用并显示 "Invalid Date"。 我不知道,为什么!

有人可以帮我吗?

/* Does your browser support geolocation? */
if ("geolocation" in navigator) {
  $('.js-geolocation').show(); 
} else {
  $('.js-geolocation').hide();
}

/* Where in the world are you? */
$('.js-geolocation').on('click', function() {
  navigator.geolocation.getCurrentPosition(function(position) {
    getWeather(position.coords.latitude+','+position.coords.longitude); //load weather using your lat/lng coordinates
  });
});

$(document).ready(function() {  
  getWeather('Kiel',''); //@params location, woeid //Get the initial weather.
});

function getWeather(location, woeid) {
  $.simpleWeather({
    //20065908 KIEL woeid
    location: location,
    woeid: woeid,
    unit: 'c',
    success: function(weather) {
      html = '<ul>Today: <i class="icon-'+weather.code+'"></i><br />';
      html += '<li>'+weather.temp+'&deg;'+weather.units.temp+'</li>';
      html += '<li>'+weather.city+', '+weather.region+'</li></ul>';

      //Don't forget to include the moment.js plugin.
      var timestamp = moment(weather.updated);
      html += '<p>Weather updated '+moment(timestamp).fromNow()+'</p>';
      html += '<p>Weather updated at '+moment(timestamp).format('MM/DD/YY h:mma')+'</p>';

      for(var i=0;i<weather.forecast.length;i++) {
        html += ''+weather.forecast[i].day+': <i class="icon-'+weather.forecast[i].code+ '"></i>';
      }

      $("#weather").html(html);
    },
    error: function(error) {
      $("#weather").html('<p>'+error+'</p>');
    }
  });
}

codepen

我不知道地理定位究竟是如何工作的...但我认为 moment.js 使用地理定位来设置语言。 所以我尝试将 moment.js locale globe 设置为 'en',但它也没有像我预期的那样工作。

问题是 Yahoo Weather(simpleWeather 的数据源)没有遵循自己的日期格式标准...响应中的 weather.updated 日期如下所示:Tue, 20 Oct 2015 3:58 pm CEST。这不是标准的日期格式,因此 Moment.js 无法正确解析(因为有一些不唯一的 time zone abbreviations,例如 CST)。

引自Yahoo Dev documentation:

pubDate: The date and time this forecast was posted, in the date format defined by RFC822 Section 5, for example Mon, 25 Sep 17:25:18 -0700.

显然,事实并非如此。 Moment.js 会很乐意解析 RFC822 格式的日期。雅虎应该解决这个问题。

但是,如果您真的想使用此功能并且您有固定的位置,可以通过更改以下行来解析来自 Yahoo 的本地日期:

var timestamp = moment(weather.updated);

对此:

var timestamp = moment(weather.updated, "ddd, DD MMM YYYY HH:mm A");

并根据访问者的时区更正此日期。