Moment returns invalid data even though date is correct

后端 未结 1 1737
轻奢々
轻奢々 2021-01-29 03:01

I have the following code

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


        
相关标签:
1条回答
  • 2021-01-29 03:49

    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>

    0 讨论(0)
提交回复
热议问题