0

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?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
robdev91
  • 1,006
  • 1
  • 10
  • 18

1 Answers1

2

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; }
iAmOren
  • 2,760
  • 2
  • 11
  • 23