Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date Now (UTC) in yyyy-mm-dd HH:mm:ss format

My brain must be utterly fried, but I cannot for the life of me figure out how to get the current date and time in UTC formatted as a string. No matter what I do, I just get local.

I have the following function which returns the date in the correct format, but it's always local.

let datenow = new Date;

console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"

function generateDatabaseDateTime(date) {
  const p = new Intl.DateTimeFormat('en', {
    year:'numeric',
    month:'2-digit',
    day:'2-digit',
    hour:'2-digit',
    minute:'2-digit',
    second:'2-digit',
    hour12: false
  }).formatToParts(date).reduce((acc, part) => {
    acc[part.type] = part.value;
      return acc;
  }, {});

  return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}

Does anyone know what I'm missing?

like image 772
Josh Avatar asked Sep 11 '25 01:09

Josh


1 Answers

We should use in-built toISOString function to covert it to ISO date format and remove not required data using string manipulation.

let datenow = new Date();

console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"

function generateDatabaseDateTime(date) {
  return date.toISOString().replace("T"," ").substring(0, 19);
}

Ideally solution should be to use momentjs or dayjs library.

like image 158
Vivek Avatar answered Sep 13 '25 14:09

Vivek