-2

I'm storing the ISO datetime value in database and when is use the new Date() method it is showing wrong date.

When I use new Date().toISOString() output is 2021-05-05T13:33:35.673Z and when is use new Date(event.date).toISOString() output is 2021-05-05T18:47:00.000Z.

But when I try new Date().getDate() the output is 5, but for new Date(event.date).getDate() the output is 6. Why is it 6 instead of 5?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Ishan Joshi
  • 151
  • 3
  • 19

1 Answers1

2

The confusion here is that getDate uses your local timezone, but toISOString shows you the information in UTC.

If you want the same day value that's in the ISO string (which is in UTC), use getUTCDate:

console.log(new Date("2021-05-05T18:47:00.000Z").getUTCDate());
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • getting answer 3 ;( – Ishan Joshi May 05 '21 at 13:54
  • @IshanJoshi - Not with the code above and the input you've described you won't. I'm guessing you accidentally used `getUTCDay` (day of week), not `getUTCDate` (day of month). (`getUTCDay` will indeed give you 3, because the 5th is Wednesday and it's 0 = Sunday, 1 = Monday, ...) – T.J. Crowder May 05 '21 at 13:55
  • ya got it thank you. So dumb mistake. it took me 30 min – Ishan Joshi May 05 '21 at 13:59
  • I'm getting the wrong date. It's November 25th 2022 at the time I'm writing this and when I run your codes, it returns November 5th 2022. I'm having the same issue in my program atm. – Grogu Nov 25 '22 at 23:02
  • @Grogu - It sounds like your string isn't quite in the format above. If it were, the results would be reliable. [The format](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-time-string-format) is year, month, day, the letter T, hour, minutes, seconds, a `.`, milliseconds, and the letter `Z` for UTC. Everything is two digits except year (four) and milliseconds (three). – T.J. Crowder Nov 27 '22 at 10:13