-1

I need to convert a date like this one: Fri Jul 28 2023 00:00:00 GMT+0200 (Central European Summer Time) Into a date like this: 2023-07-26 or viceversa using javascript, is it possible or impossible?

Shadq
  • 25
  • 5

1 Answers1

-1
const inputDate = "Fri Jul 28 2023 00:00:00 GMT+0200 (Central European Summer Time)";
const dateObject = new Date(inputDate);
const year = dateObject.getFullYear();
const month = String(dateObject.getMonth() + 1).padStart(2, '0');
const day = String(dateObject.getDate()).padStart(2, '0');
const resultDate = `${year}-${month}-${day}`;

console.log(resultDate); // Output: "2023-07-28"

Reverse:

const inputDate = "2023-07-28";
const dateObject = new Date(inputDate);
const options = { weekday: 'short', month: 'short', day: '2-digit', year: 'numeric', timeZoneName: 'short' };
const resultDate = dateObject.toLocaleString('en-US', options);

console.log(resultDate);
Mpmp
  • 249
  • 2
  • 4
  • Dates in the format YYYY-MM-DD are parsed as UTC, so for systems with timezone west of Greenwich, the "reverse" solution will produce a date that is 1 day earlier. Also, `dateObject.toLocaleString('en-US', options)` will not produce a result the same as the original timestamp. `timeZoneName: 'short'` will produce different results in different implementations and depending on the default language.. – RobG Jul 27 '23 at 11:16
  • @RobG I'll be glad to see your solution. – Mpmp Jul 27 '23 at 16:12