Is the Javascript date object always one day off?

后端 未结 23 2323
既然无缘
既然无缘 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条回答
  • 2020-11-22 02:29

    Your log outputs GMT so you want to specify your timezone:

    var doo = new Date("2011-09-24 EST");
    
    0 讨论(0)
  • 2020-11-22 02:32

    if you need a simple solution for this see:

    new Date('1993-01-20'.split('-')); 
    

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 02:32

    The best way to handle this without using more conversion methods,

     var mydate='2016,3,3';
     var utcDate = Date.parse(mydate);
     console.log(" You're getting back are 20.  20h + 4h = 24h :: "+utcDate);
    

    Now just add GMT in your date or you can append it.

     var  mydateNew='2016,3,3'+ 'GMT';
     var utcDateNew = Date.parse(mydateNew);
     console.log("the right time that you want:"+utcDateNew)
    

    Live: https://jsfiddle.net/gajender/2kop9vrk/1/

    0 讨论(0)
  • 2020-11-22 02:34

    Though in the OP's case the timezone is EDT, there's not guarantee the user executing your script will be int he EDT timezone, so hardcoding the offset won't necessarily work. The solution I found splits the date string and uses the separate values in the Date constructor.

    var dateString = "2011-09-24";
    var dateParts = dateString.split("-");
    var date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
    

    Note that you have to account for another piece of JS weirdness: the month is zero-based.

    0 讨论(0)
提交回复
热议问题