如何在 MomentJS 中将日期转换为 UNIX 时间戳?

如何在 MomentJS 中将日期转换为 UNIX 时间戳?

问题描述:

我想将我的日期时间值转换为 Unix 时间戳格式(基本上是纪元时间戳).为此,我使用:

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();

但是它给了我一个错误

错误类型错误:无法读取未定义的属性 'Unix'

ERROR TypeError: Cannot read property 'Unix' of undefined

谁能告诉我如何使用 MomentJS 将日期时间转换为 Unix?

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

问题是因为您在纯字符串上调用 unix().您需要在 MomentJS 对象上调用它.要创建这些,您可以将日期字符串提供给 MomentJS 构造函数,如下所示:

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>