简体   繁体   中英

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.

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

Prints 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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