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?

1
  • 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: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 9, 2022 at 9:43

3 Answers 3

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()

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

3 Comments

FYI: Instead of GMT+00 you can also just write UTC
Correct, I personally like this more because I know which timezone it is, feel more explicit for me.
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").
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()

Comments

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

1 Comment

Or just date.toLocaleDateString('en-CA'). ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.