0

Why when I create without space in javascript console is to the yesterday date at 9:00PM, but when I write with a space in the end the date and hour is ok?

new Date('2021-07-20')

Wrong: Mon Jul 19 2021 21:00:00


new Date('2021-07-20 ')

Correct: Tue Jul 20 2021 00:00:00

Dominik
  • 6,078
  • 8
  • 37
  • 61
  • I can't reproduce this. What environment are you using here? Browser? What kind? – Dominik Jul 27 '21 at 21:45
  • In Chrome terminal and ReactJS. – Assis Duarte Jul 27 '21 at 21:48
  • Edit your question and use the snippet function with console.log. In Firefox the date with space will return an error. – Dominik Jul 27 '21 at 21:49
  • I can see difference in Node.js and Chrome, but see [Date() constructor -Timestamp string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#timestamp_string): "Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies." – vsemozhebuty Jul 27 '21 at 21:51

2 Answers2

3

2021-07-20 is a valid ISO time. It gets parsed as 20th July 2021 at midnight UCT. It then gets converted to local time for you which (in Porto Alegre) is three hours earlier.

2021-07-20 is not a valid ISO time, so it hits your JS engine's implementation-specific parser for non-standard date formats.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You shoud use , between them like: const d = new Date(2018, 11, 24, 10, 33, 30); And remember JavaScript counts months and days from 0 to 11 just like indexes.

Alireza
  • 9
  • 4