moment.utc doesn't work in IE and Safari

2020-03-31 10:07发布

问题:

I am trying to convert Dropbox API date format to date one. In moment.js,

It doesn't work in following format now.

moment.utc("Sat, 21 Aug 2010 22:31:20 +0000")

It does work in following format if using date convert before using utc:

moment.utc(new Date("Sat, 21 Aug 2010 22:31:20 +0000"))

However, I can't use new Date method, because it can't be used in some other cases (string is not standardized) -- related Stackoverflow question.

One possible way is to configure Dropbox input format, is there any other method to let moment.utc work without using new Date method?

Thanks very much!

回答1:

In the official docs of Moment.js, it says:

moment(String);

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.

Therefore, in order to go around the new Date pitfall and also apply ISO 8061. I can apply moment() firstly and then apply utc().

moment("Sat, 21 Aug 2010 22:31:20 +0000").utc()

In that case, although the input string is not formatted as the same(But all follow ISO 8061), they can still be processed safely.



回答2:

Moments.js issues a big fat Deprecation warning on your code. The gist of the problem is this: if you don't provide an explicit date format, and your date format is not an ISO 8061 lookalike, moment.js gives up on parsing it and relies on new Date() in stead. Which is brittle at best.

The solution is simple: you know the format Dropbox uses to return your date in. Simply specify it, and your problem is solved. Something like (actual format may need some tweaking)

var value = moment.utc("Sat, 21 Aug 2010 22:31:20 +0000", "ddd, d MMM YYYY HH:mm:ss Z");


回答3:

var d = moment.utc("20100821", "YYYYMMDD");
var day = d.day(); // 6
var year = d.year(); // 2010
var month = d.month(); // 7
var date = d.date(); // 21