从UTC字符串创建时刻对象 [英] Create moment Object from UTC string

查看:97
本文介绍了从UTC字符串创建时刻对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的网络服务中得到一个UTC日期字符串如下:
2015-06-06T12:30:12Z



我需要按照这两个规则显示:


  1. 如果date< 1周,显示为:3天前或23分钟前....

  2. 如果日期> 1周,显示日期 YYYY-DD-MM

现在我正在尝试构建一个时间对象,但似乎返回一些奇怪的东西:

  var sDate =2015-06-06T12:30:12Z; 
var momentDate = moment(sDate);
var fromNow = momentDate.fromNow();
console.log(momentDate:+ momentDate); // 1433593812000
console.log(fromNow:+ fromNow); //11å°æ™,å‰

你有什么想法如何实现吗? p>

谢谢。

解决方案

您只是遇到一个已经记录的错误作为#2367



简单来说,它使用最后一个区域设置(zh-tw),而不是默认为英文。



只需在加载时点击添加以下行,但是在任何地方使用它之前。

  moment.locale('en'); 

将语言设置为英文。



这解释了 fromNow 字符串的输出。另一个输出是因为您将时刻对象直接连接到另一个字符串,隐式调用 .valueOf(),它以毫秒为单位返回基于UTC的时间戳。您应该使用 .format(),或许有一个参数,例如 .format(YYYY-MM-DD) - 如果这是你想看到的输出格式。


I'm getting from my webservice an UTC date String such as the following : "2015-06-06T12:30:12Z"

I need to display it following these 2 rules :

  1. If date < 1 week, display it like : 3 days ago or 23 mins ago....
  2. If date > 1 week, display the date YYYY-DD-MM

Now I'm trying to build a moment object but seems to be returning something weird :

var sDate = "2015-06-06T12:30:12Z";
var momentDate = moment(sDate);
var fromNow = momentDate.fromNow();
console.log("momentDate : " + momentDate);    // 1433593812000
console.log("fromNow : " + fromNow);    // 11å°æ™‚å‰

Do you have any idea how to achieve this ?

Thanks.

解决方案

You're just hitting a bug, already logged as #2367.

Stated very simply, it's using the last locale loaded ("zh-tw"), rather than defaulting to English.

Simply call add the following line after you load moment but before you use it anywhere.

moment.locale('en');

This sets the language back to English.

That explains the output of the fromNow string. The other output is because you concatenated the moment object directly with another string, which implicitly calls .valueOf(), which returns the UTC-based timestamp in milliseconds. You should instead use .format(), perhaps with an argument such as .format("YYYY-MM-DD") - if that's the output format you would like to see.

这篇关于从UTC字符串创建时刻对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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