将TimeStamp转换为DateTime

时间:2016-12-09 15:16:06

标签: javascript datetime timestamp

我正在使用OpenWeatherMap API,我正在尝试检索LastUpdated属性。

让我重新说一下,我可以检索LastUpdated属性,但是使用JSON格式时它会作为时间戳。

如何将该时间戳转换为正常日期/时间以显示给用户?

我做了一些研究并下载了Moment.js,但是当我运行该页面时,我收到一条错误消息:

  

错误:对象不支持属性或方法'格式'

这是我的代码:

<script src="~/Scripts/moment.js"></script>
<script>
    $(document).ready(function () {
        var request = $.ajax({
            url: "http://api.openweathermap.org/data/2.5/weather",
            method: "GET",
            data: { id: '4142290', appid: 'myapikey', units: 'imperial' },
            success: function (response) {
                console.log(response);
                var weatherIcon = response.weather[0].icon;
                var weatherDescription = response.weather[0].description;
                var weatherTemp = response.main.temp;
                var lastUpdated = response.dt;
                var formatted = lastUpdated.format("dd.mm.yyyy hh:MM:ss");

                var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png";
                document.getElementById('Weather-Image').src = iconUrl;
                document.getElementById('Weather-Description').innerHTML = "[" + weatherDescription + "]";
                document.getElementById('Weather-Temp').innerHTML = weatherTemp;
                document.getElementById('Weather-Updated').innerHTML = formatted;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText)
            }
        });
    });
</script>

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您正试图致电Moment.js&#39;时间戳上的Undo, Redo, Cut, Copy, Paste, etc... 方法,而不是时刻的实例

首先需要解析返回的时间戳,然后以您需要的样式对其进行格式化。

format

假设var formatted = moment(response.dt).format("dd.mm.yyyy hh:MM:ss"); 是moment.js(docs

的解析函数支持的格式