【问题标题】:Convert TimeStamp To DateTime将时间戳转换为日期时间
【发布时间】:2017-04-25 02:42:00
【问题描述】:

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

感谢任何帮助。

【问题讨论】:

标签: javascript datetime timestamp


【解决方案1】:

您试图在时间戳上调用 Moment.js 的 format 方法,而不是 Moment

的实例

您首先需要解析返回的时间戳,然后将其格式化为您需要的样式。

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

假设response.dt是moment.js(docs)的解析函数支持的格式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2020-10-19
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多