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.
Call unix()
on moment
object. Reference .
moment('2020-12-12').unix()
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>
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, ie YYYY-MM-DD you do not need to provide the input date format to the moment constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.