问题
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