Is the Javascript date object always one day off?

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

提交回复
热议问题