解析utc时,fromNow的瞬间将在5小时内返回 [英] moment fromNow returns in 5 hours when parsing utc

查看:98
本文介绍了解析utc时,fromNow的瞬间将在5小时内返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用fromNow的moment.js从服务器上格式化utc时间,但有时我会在"5个小时内"得到.

trying to format utc time from server in time ago using moment.js fromNow but in some occasions I get "in 5 hours" instead.

时间戳-2017-11-29T15:03:21

timestamp from a server - 2017-11-29T15:03:21

var utcTime = new Date(timestamp);
var timeAgo = moment(utcTime).fromNow();    
console.log(timeAgo)

所有日期都过去了,所以我该如何解决这个问题,以便在几个小时内没有时间?

all dates are in past so how can I fix this so I dont get time in a few hours ?

推荐答案

如果要将"2017-11-29T15:03:21"视为UTC,则可以使用moment的 utc 方法,也可以只需在字符串后附加一个"Z"即可.由于您已经在使用moment.js,因此使用moment.js进行解析比内置解析器更可靠:

If you want "2017-11-29T15:03:21" treated as UTC, you can either use moment's utc method or just append a "Z" to the string. Since you're already using moment.js, it's more reliable to parse it with moment.js than the built-in parser:

var timestamp = "2017-11-30T00:20:48";

// Append Z
console.log(moment(timestamp + 'Z').fromNow());

// Use .utc
console.log(moment.utc(timestamp).fromNow());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>

这篇关于解析utc时,fromNow的瞬间将在5小时内返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆