-1

I am getting an odd behavior if I pass the Date constructor just a date string. Example:

    <div>Date 1: <span id="mydate1"></span></div>
    <div>Date 2: <span id="mydate2"></span></div>
    <div>Date 3: <span id="mydate3"></span></div>
    <script>
        document.getElementById("mydate1").innerHTML = (new Date("2022-06-28 20:32:00")).toString();
        document.getElementById("mydate2").innerHTML = (new Date("2022-06-28")).toString();
        document.getElementById("mydate3").innerHTML = (new Date("2022-06-28 00:00:00")).toString();
    </script>

This results in the following:

Date 1: Tue Jun 28 2022 20:32:00 GMT-0400 (Eastern Daylight Time)
Date 2: Mon Jun 27 2022 20:00:00 GMT-0400 (Eastern Daylight Time)
Date 3: Tue Jun 28 2022 00:00:00 GMT-0400 (Eastern Daylight Time)

Date 1 works as I would expect. But why are Date 2 and 3 different? With just a date string, it seems to be inferring the date is in UTC, where as with a time field it seems to assume it is in my locale time.

Any thoughts? I can work around it by appending the 00:00:00 text.

Dave Hubbard
  • 469
  • 5
  • 11
  • 1
    "*But why are Date 2 and 3 different?*" answered by "*With just a date string, it seems to be inferring the date is in UTC, where as with a time field it seems to assume it is in my locale time.*" – VLAZ Dec 12 '22 at 21:28
  • 1
    Have you read the [documentation of `Date` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#date_string)? – axiac Dec 12 '22 at 21:35
  • Ah. Helps to read the fine print. Still odd, but it is what it is. – Dave Hubbard Dec 13 '22 at 13:52

1 Answers1

2

It is explained in the documentation of Date constructor, when the argument is a date string:

Date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local.

axiac
  • 68,258
  • 9
  • 99
  • 134