Siddu Palaparthi
Siddu Palaparthi

Reputation: 89

How to convert Moment.js moment to unix timestamp

I see a lot in the Moment.js documentation about getting a Moment from a Unix timestamp. However, I am trying to convert a Moment to a Unix timestamp, and I am not sure how to do that. This is how my moment looks:

const myMomentObject = moment(str_time, 'YYYY-MM-DD');

And I need to convert it to a Unix timestamp.

Upvotes: 2

Views: 6359

Answers (3)

thisdotutkarsh
thisdotutkarsh

Reputation: 980

To create a Unix timestamp (seconds since the Unix Epoch) from a moment, use the following,

console.log(moment('2021-10-16').unix());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Since your date format follows the ISO_8601 format, i.e. YYYY-MM-DD you do not need to provide the input date format to the moment constructor.

Upvotes: 1

Charlie
Charlie

Reputation: 23858

Unix timestamp can be obtaineded with or without the moment library.

//Moment
const myMomentObject = moment('2021-10-16', 'YYYY-MM-DD');
console.log(myMomentObject.unix());


//Vanilla
const d = new Date('2021.10.16');
console.log(d.getTime() / 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Upvotes: 3

msrumon
msrumon

Reputation: 1440

Call unix() on moment object. Reference.

moment('2020-12-12').unix()

Upvotes: 3

Related Questions