How to convert dates to UNIX timestamps in MomentJS?

半城伤御伤魂 提交于 2021-02-05 07:52:06

问题


I want to convert my date time values to Unix timestamp format (basically an epoch timestamp). For that I use:

let startDate = '2018-09-28 11:20:55';
let endDate = '2018-10-28 11:20:55';
let test1 = startDate.unix();
let test2 = endDate.unix();

However it gives me an error

ERROR TypeError: Cannot read property 'Unix' of undefined

Can anyone tell me how I can convert datetime to Unix using MomentJS?


回答1:


The issue is because you're calling unix() on plain strings. You need to instead call it on MomentJS objects. To create those, you can provide the date strings to a MomentJS constructor, like this:

let startDate = '2018-09-28 11:20:55';
let endDate = '2018-10-28 11:20:55';

let test1 = moment(startDate).unix();
let test2 = moment(endDate).unix();

console.log(test1);
console.log(test2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script>


来源:https://stackoverflow.com/questions/52534135/how-to-convert-dates-to-unix-timestamps-in-momentjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!