将时间戳转换为日期时间

灰熊

我正在使用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>

任何帮助表示赞赏。

乔丹·伯内特(Jordan Burnett)

您正在尝试format在时间戳而不是Moment实例上调用Moment.js的方法

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

var formatted = moment(response.dt).format("dd.mm.yyyy hh:MM:ss");

假设这response.dt是moment.js(docs的解析功能支持的格式

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章