如何在 MomentJS 中将日期转换为 UNIX 时间戳? [英] How to convert dates to UNIX timestamps in MomentJS?

查看:107
本文介绍了如何在 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>

这篇关于如何在 MomentJS 中将日期转换为 UNIX 时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆