LogiStack
LogiStack

Reputation: 1016

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?

Upvotes: 1

Views: 261

Answers (1)

iAmOren
iAmOren

Reputation: 2804

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; }

Upvotes: 2

Related Questions