简体   繁体   中英

Convert String to DateTime Javascript

I have got a problem in displaying PHP formatted date/time string into a customized format in JavaScript.

The date/time string looks like Monday 21st September 2020

Anyone who knows how to simply handle this?

This is what I came up with - WITHOUT LIBRARIES:

 var dateString = "Monday 21st September 2020"; var dayOfMonth, month, year; [, dayOfMonth, month, year] = dateString.split(" "); var date = new Date([dayOfMonth.match(/\\d*/)[0], month, year]); console.log("date:\\n" + date);

The idea is to split the date string into it's 4 parts using destructor, and ignoring the first (day of week).
Extracting the digits from the day of month (with st/nd/rd/th) with regex.
Putting things back into a new Date.

And as a function:

 function dateStringToDate(dateString) { var dayOfMonth, month, year; [, dayOfMonth, month, year] = dateString.split(" "); return new Date([dayOfMonth.match(/\\d*/)[0], month, year]); } var dates = [ "Monday 21st September 2020", "Erich_Kästner 35th May 1931", "Someday 2nd October 1967" ]; for(var d = 0; d < dates.length; d++) { console.log(dates[d]+":\\n" + dateStringToDate(dates[d])); }
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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