简体   繁体   English

使用 Date 或 Moment.js 将字符串转换为日期

[英]Convert a string to a date with Date or Moment.js

I have a string that I want to convert into a date to compare it to the current date and hour (local time).我有一个字符串,我想将其转换为日期以将其与当前日期和小时(当地时间)进行比较。 The string format is like this:字符串格式是这样的:

2020-06-09 11:25 pm

And I want to use either Date or Moment.js to format it to a Date object, but so far I haven't had any luck.我想使用 Date 或 Moment.js 将其格式化为Date object,但到目前为止我还没有运气。

const date = new Date(`${eventDayFinish} ${eventHourFinish}`);

Prints Date { NaN }打印Date { NaN }

Any help will be appreciated.任何帮助将不胜感激。

Use the moment this way.以这种方式利用这一刻。

let d = moment('2020-06-09 11:25 pm', 'YYYY-MM-DD HH:mm a').format();
console.log(new Date(d));
// Tue Jun 09 2020 23:25:00 GMT+0530 (India Standard Time)

在此处输入图像描述


Explanation:解释:
Moment takes the second argument as the format of the input date string, you can give any format to it, along with the format you passed, it will return you the date object. Moment 将第二个参数作为输入日期字符串的格式,你可以给它任何格式,连同你传递的格式,它会返回日期 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM