Is the Javascript date object always one day off?

后端 未结 23 2619
既然无缘
既然无缘 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:21

    I encountered this exact problem where my client was on Atlantic Standard Time. The date value the client retrieved was "2018-11-23" and when the code passed it into new Date("2018-11-23") the output for the client was for the previous day. I created a utility function as shown in the snippet that normalized the date, giving the client the expected date.

    date.setMinutes(date.getMinutes() + date.getTimezoneOffset());

    var normalizeDate = function(date) {
      date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
      return date;
    };
    
    var date = new Date("2018-11-23");
    
    document.getElementById("default").textContent = date;
    document.getElementById("normalized").textContent = normalizeDate(date);

    Calling new Date("2018-11-23")


提交回复
热议问题