Home » Php » php – How to create date from a specified format in JavaScript similar to DateTime::createFromFormat

php – How to create date from a specified format in JavaScript similar to DateTime::createFromFormat

Posted by: admin February 25, 2020 Leave a comment

Questions:

I expect to get a date from my database in Ymd format.
This gives me values like 20200202. This is fine for php applications but I’m using JavaScript for the frontend.

In php, we could do something like

$date = DateTime::createFromFormat('Ymd', '20200202');

meaning I get a date object as long as the formats match.

Is there a way for JavaScript to do this?

How to&Answers:

If you are sure this date will always come in the format yyyymmdd, you can use RegEx to extract the date :

function getDate(inputDate)
{
  // TODO : Check if the format is valid
  
  
  const pattern = /(\d{4})(\d{2})(\d{2})/
  
  const parts = inputDate.match(pattern);
  
  // months start with 0 in js, that's why you need to substract 1
  // -----------------------v----------v
  return new Date(parts[1], parts[2] - 1, parts[3]);
}

console.log(getDate("20200202").toString());
console.log(getDate("20200213").toString());
console.log(getDate("20201231").toString());

Answer:

You could always check if the format matches your requirements and then split the value you get from the database. Then you could either return a Boolean value false if not possible or a date.

const dbOutput = '20200202';

const createdDate = getDate(dbOutput);


function getDate(value) {
    if(value.length !== 8) {
        return false;
    }

    const year = +value.substring(0,4);
    const month = +value.substring(4,6);
    const day = +value.substring(6,8);

    try {
        return new Date(year, month-1, day);
    } catch (error) {
        return false;
    }
}