1

I'm trying to understand how javascript's Date api acts when parsing the date and I cant justify the way javascript parse same dates but different formats into different dates.

const date1 = new Date('2020-05-13');
const date2 = new Date('2020-12-28');

const date1Reversed = new Date('05-13-2020');
const date2Reversed = new Date('05-28-2020');

console.group('Date Format: YYYY-MM-DD')
console.log(date1);
console.log(date2);
console.groupEnd();

console.group('Date Format: MM-DD-YYYY')
console.log(date1Reversed);
console.log(date2Reversed);
console.groupEnd();

Above code gives below output

Date Format: YYYY-MM-DD
  2020-05-13T00:00:00.000Z
  2020-12-28T00:00:00.000Z
Date Format: MM-DD-YYYY
  2020-05-12T21:00:00.000Z
  2020-05-27T21:00:00.000Z

Dates are identical but the mm-dd-yyyy date parsed into GMT-3, what is the logic behind this ?

Teoman Tıngır
  • 2,766
  • 2
  • 21
  • 41
  • 1
    FWIW, my browser gives `null` for the last two… TL;DR: if the format is *non-standard*, there's no specific answer you can expect (by definition), and every browser will fail in different ways. – deceze Aug 17 '20 at 08:25
  • Is GMT+03:00 your current computer's time zone? – Álvaro González Aug 17 '20 at 08:27
  • I think that has something to do with timezones. For you the second batch is 3h behind, on my browser its just 2. Cant say what the problem is exactly though. – MauriceNino Aug 17 '20 at 08:27
  • @ÁlvaroGonzález yes it is – Teoman Tıngır Aug 17 '20 at 08:28
  • 2
    You have a good overview at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#Timestamp_string). – Álvaro González Aug 17 '20 at 08:28
  • Momentjs is a good tool to deal with dates: https://momentjs.com/ – TDAK Aug 17 '20 at 08:29
  • @ÁlvaroGonzález thank you for the reference. – Teoman Tıngır Aug 17 '20 at 08:33
  • 1
    The logic is that the TC39 decided that YYYY-MM-DD format dates should be parsed as UTC whereas common use and ISO 8601 parse them as local following the convention that dates and date/times without an offset are local. – RobG Aug 17 '20 at 23:42

0 Answers0