2015-10-15 54 views
0

嘿嗬=)simpleWeather和moment.js - 無效的日期與JS-地理位置德國

我想創造一個天氣插件,我的網站。所以我選擇了simpleWeather插件。

的simpleWeather插件使用的moment.js LIB得到最後更新的時間。但插件本身不提供語言選項。

我的標準位置是「德國基爾」。

但它不工作,並說「無效的日期」。 我不知道,爲什麼!

有人可以幫我嗎?

/* 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 globaly區域設置成「en」,但它也沒有工作,我沒有料到。

回答

0

問題是,雅虎天氣(simpleWeather的數據源)沒有按照自己的日期格式化標準...響應中的weather.updated日期如下所示:Tue, 20 Oct 2015 3:58 pm CEST。這不是一個標準日期格式,從而Moment.js無法分析是正確的(因爲有一些不是唯一time zone abbreviations,例如CST)。

Yahoo Dev documentation引述:

發佈時間:的日期和這個預測被張貼在由RFC822第5節中定義的 日期格式,例如星期一時間,9月25日17時25 : 18 -0700。

顯然,這並非如此。 Moment.js會高興地解析RFC822格式化的日期。雅虎應該解決這個問題。

但是,如果你真的想使用此功能,你有一個固定的位置,有一種方法,通過改變這一行來解析來自雅虎的本地日期:

var timestamp = moment(weather.updated); 

這樣:

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

並根據訪客的時區更正此日期。

+0

謝謝,詳細的答案!這工作完美! –