0

I want to obtain a date in yyyy-mm-dd format from a JavaScript Date object.

new Date('Aug 5 2022').toISOString().split('T')[0]

From above line, I'm expecting 2022-08-05 but getting 2022-08-04

how to solve it?

Amin
  • 681
  • 4
  • 9
  • 27
  • 3
    `"Aug 5 2022"` is not in a format defined to be parseable by the spec. While it's possible that a certain implementation might recognize and handle this format, it is not guaranteed. See here for info about valid datestring formats including a link to the specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#datestring – jsejcksn Aug 09 '22 at 09:43

3 Answers3

1

This issue occurs because you try to convert to toISOString it automatically convert to UTC, I am confident you are not in UTC area. So to fix this use:

new Date('Aug 5 2022 GMT+00').toISOString().split('T')[0]

So, convert it to UTC then to toISOString()

Reyno
  • 6,119
  • 18
  • 27
owenizedd
  • 1,187
  • 8
  • 17
  • FYI: Instead of `GMT+00` you can also just write `UTC` – Reyno Aug 09 '22 at 09:36
  • Correct, I personally like this more because I know which timezone it is, feel more explicit for me. – owenizedd Aug 09 '22 at 09:37
  • See @jsejcksn's comment to the OP. `new Date().toLocaleDateString('en-CA')` does the job without relying on parsing an unsupported format. There are a number of languages that will produce the same result (such as "sv"). – RobG Aug 09 '22 at 11:53
0

Your date gets converted to UTC. One way to fix this would be by adding UTC to your argument string.

new Date('Aug 5 2022 UTC').toISOString().split('T')[0]

Date.prototype.toISOString()

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix Z. - Date.prototype.toISOString()

Behemoth
  • 5,389
  • 4
  • 16
  • 40
0

Below are two ways to get the yyyy-mm-dd string format that you asked about from a native JavaScript Date object:

  1. Offsetting the date information according to the system time UTC offset:

const date = new Date();
const utcOffsetMs = date.getTimezoneOffset() * 60 * 1e3 * -1;
const offsetDate = new Date(date.getTime() + utcOffsetMs);
const dateStr = offsetDate.toISOString().slice(0, 10);

console.log(dateStr);
  1. Get the individual date parts and format them with a leading 0 if necessary:

function getDateString (date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const dayOfMonth = date.getDate();
  return `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`;
}

const date = new Date();
const dateStr = getDateString(date);

console.log(dateStr);
jsejcksn
  • 27,667
  • 4
  • 38
  • 62