javascript - How to convert Moment.js moment to unix timestamp - Stack Overflow

I see a lot in the Moment.js documentation about getting a Moment from a Unix timestamp. However, I am

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.

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.

Share Improve this question asked Oct 16, 2021 at 5:26 Siddu PalaparthiSiddu Palaparthi 891 gold badge3 silver badges11 bronze badges 2
  • Did you try doing moment('str_time', "YYYY-MM-DD").unix() ? – thisdotutkarsh Commented Oct 16, 2021 at 5:31
  • 1 Just remember: the moment.js documentation also says to stop using it, because time passed it by =) – Mike 'Pomax' Kamermans Commented Oct 16, 2021 at 5:50
Add a ment  | 

3 Answers 3

Reset to default 3

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./ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Call unix() on moment object. Reference.

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

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./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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744059781a4551568.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信