Create moment Object from UTC string

こ雲淡風輕ζ 提交于 2020-01-17 04:41:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/30688475/create-moment-object-from-utc-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!