javascript - 将日期作为特定格式的字符串传递并使用 momentjs 返回日期对象的正确方法是什么?

标签 javascript momentjs

我一直在看momentjs momenjs文档,因为我想用它从日期返回日期对象,该日期是特定格式的字符串。我的代码如下所示。

const date = moment(stringDate, 'YYYY-MM-DD HH:MM:SS');
console.log(date);

但它创建了一个无效日期,如此处所示。

produces invalid date

我做错了什么。如何从特定格式的日期字符串中获取日期对象?

最佳答案

您使用 MM:SS 表示分钟:秒,但它应该是 mm:ssdetails here .

示例:

const stringDate = "2018-05-11 14:25:37";
// Parsing
const m = moment(stringDate, 'YYYY-MM-DD HH:mm:ss');
// Show it in a different format to demonstrate parsing worked
console.log(m.format("DD/MM/YYYY HH:mm"));
// Accessing the underlying Date object
const dt = m.toDate();
// Log that dateobject
console.log(dt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

关于javascript - 将日期作为特定格式的字符串传递并使用 momentjs 返回日期对象的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50293214/

相关文章:

javascript - 为什么页面刷新会触发.keyup()?

javascript - 使用 Casper/Phantom 读取 HTML 属性因环境而异

javascript - 如何组合对象数组中的每个值?

javascript - 尝试在 Django 中构建一个使用 chessboard.js 显示棋盘的网页

javascript - Moment.js 在 Firefox 中返回 NaN 而不是 chrome

javascript - Bootstrap 下拉列表按钮作为表单元素

javascript - 分钟操作后 Momentjs 返回错误的日期

javascript - 如何将时刻日期从时隙拆分为数组?

javascript - 使用 moment.js 倒计时到特定的日期和时间

javascript - Moment.js 无法正确计算两个日期之间的周数