Moment returns invalid data even though date is co

2019-03-04 17:44发布

问题:

I have the following code

var value = 1504528441;
var utcDateTime = moment.utc(value, "YYYY-MM-DD HH:mm:ss")

and I get Invalid date.

I tried converting this number on https://www.epochconverter.com/ and it seems to be converting just fine.

I don't understand what is the problem with moment.

回答1:

You are using the wrong method and confusing between parsing input and showing moment object value.

There is no moment.utc(Number, String) and moment.utc(Number) creates a moment object treating Number input parameter as milliseconds since the Unix Epoch (Jan 1 1970 12AM UTC).

You have to use moment.unix(Number) since your value input is seconds since Unix epoch:

To create a moment from a Unix timestamp (seconds since the Unix Epoch), use moment.unix(Number).

Then you can use format() to show the value of your moment object in the format you prefer (e.g. "YYYY-MM-DD HH:mm:ss").

Here a working sample:

var value = 1504528441;
var utcDateTime = moment.unix(value);
console.log( utcDateTime.format("YYYY-MM-DD HH:mm:ss") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>



标签: momentjs