Matt Dell
Matt Dell

Reputation: 9539

Cannot initialize a moment instance with a unix timestamp generated from moment (Invalid date)

I'm confused about these two code samples

Assuming we have a Unix timestamp generated from moment

moment().format('x');

Result: 1441721685361

Code snippet 1

moment(1441721685361);

Result: moment object with date Tue Sep 08 2015 15:14:45 GMT+0100 (BST)

Code snippet 2

moment(moment().format('x'));

Result: Invalid date

If moment().format('x') returns an integer why can't I then use it within moment() ?

Upvotes: 2

Views: 1183

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77522

moment().format('x') returns string, but expect number in case when you pass timestamp, you can convert string to number (add + before or use Number(string) ) and pass to moment, like this

console.log(typeof moment().format('x'));
console.log(moment(+moment().format('x')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>

Upvotes: 2

Related Questions