1

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?

7
  • 1
    Consider searching before asking? There are many questions and answers to formatting dates in JS. Commented Oct 13, 2020 at 15:59
  • Will you please let me have a similar one? I tried, but no success. Commented Oct 13, 2020 at 15:59
  • 1
    I'm not the one stopping you from searching. This very site has hundreds of questions about JS date/time formatting. Commented Oct 13, 2020 at 16:00
  • stackoverflow.com/questions/9755911/… Commented Oct 13, 2020 at 16:02
  • @Raqha I have no access to change the API. I have to handle this part in Javascript. Commented Oct 13, 2020 at 16:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I still don't know when to use let and when to use const, so, at least, I used var...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.