Is the Javascript date object always one day off?

后端 未结 23 2376
既然无缘
既然无缘 2020-11-22 01:49

In my Java Script app I have the date stored in a format like so:

2011-09-24

Now when I try using the above value to create a new Date obje

23条回答
  •  旧时难觅i
    2020-11-22 02:32

    if you're just looking to make sure the individual parts of the date stay the same for display purposes, *this appears to work, even when I change my timezone:

    var doo = new Date("2011-09-24 00:00:00")
    

    just add the zeros in there.

    In my code I do this:

    let dateForDisplayToUser = 
      new Date( `${YYYYMMDDdateStringSeparatedByHyphensFromAPI} 00:00:00` )
      .toLocaleDateString( 
        'en-GB', 
        { day: 'numeric', month: 'short', year: 'numeric' }
      )
    

    And I switch around my timezone on my computer and the date stays the same as the yyyy-mm-dd date string I get from the API.

    But am I missing something/is this a bad idea ?

    *at least in chrome. This Doesn't work in Safari ! as of this writing

提交回复
热议问题