问题
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 :
- If date < 1 week, display it like : 3 days ago or 23 mins ago....
- 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