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.
Advertisement
Answer
Unix timestamp can be obtaineded with or without the moment library.
JavaScript
x
8
1
//Moment
2
const myMomentObject = moment('2021-10-16', 'YYYY-MM-DD');
3
console.log(myMomentObject.unix());
4
5
6
//Vanilla
7
const d = new Date('2021.10.16');
8
console.log(d.getTime() / 1000);
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>