在我的Java脚本应用程序中,我以这样的格式存储日期:

2011-09-24

现在,当我尝试使用上面的值创建一个新的Date对象(这样我就可以以不同的格式检索日期)时,日期总是返回一天。见下文:

var date = new Date("2011-09-24");
console.log(date);

日志:

Fri Sep 23 2011 20:00:00 GMT-0400 (Eastern Daylight Time)

当前回答

// When the time zone offset is absent, date-only formats such as '2011-09-24' // are interpreted as UTC time, however the date object will display the date // relative to your machine's local time zone, thus producing a one-day-off output. const date = new Date('2011-09-24'); console.log(date); // Fri Sep 23 2011 17:00:00 GMT-0700 (PDT) console.log(date.toLocaleDateString('en-US')); // "9/23/2011" // To ensure the date object displays consistently with your input, simply set // the timeZone parameter to 'UTC' in your options argument. console.log(date.toLocaleDateString('en-US', { timeZone: 'UTC' })); // "9/24/2011"

其他回答

只是想添加,显然在字符串末尾添加一个空格将使用UTC来创建。

new Date("2016-07-06")
> Tue Jul 05 2016 17:00:00 GMT-0700 (Pacific Daylight Time)

new Date("2016-07-06 ")
> Wed Jul 06 2016 00:00:00 GMT-0700 (Pacific Daylight Time)

编辑:这不是一个推荐的解决方案,只是一个替代答案。请不要使用这种方法,因为它非常不清楚正在发生什么。有很多种方法可以重构这个不小心导致错误。

你的问题是时区。注意GMT-0400部分,也就是你比GMT晚4个小时。如果在显示的日期/时间上加上4个小时,就会得到2011/09/24的零点。使用toUTCString()方法来获取GMT字符串:

var doo = new Date("2011-09-24");
console.log(doo.toUTCString());

遵循代码对我很有效。首先,我将日期和时间字符串转换为localeDateString,然后对返回的字符串应用split函数。

const dateString = "Thu Dec 29 2022 00:00:00 GMT+0500 (Pakistan Standard Time)";
const date = new Date(dateString).toLocaleDateString().split("/");
const year = new Date(dateString).getFullYear();
const month = new Date(dateString).getMonth();

console.log(new Date(`${date[2]}-${date[0]}-${date[1]}`));
// 2022-12-29T00:00:00.000Z


// Due to timezone issue, the date is one day off.
console.log(new Date("2011-09-24"));
// => 2011-09-24T00:00:00.000Z-CORRECT DATE.

console.log(new Date("2011/09/24"));
// => 2011-09-23T19:00:00.000Z -ONE DAY OFF AS BEFORE.

我解析ISO日期而不受时区困扰的解决方案是在解析它之前在结尾添加“T12:00:00”,因为当格林威治的中午时,整个世界都在同一天:

function toDate(isoDateString) {
  // isoDateString is a string like "yyyy-MM-dd"
  return new Date(`${isoDateString}T12:00:00`);
}

之前:

> new Date("2020-10-06")
> Date Mon Oct 05 2020 14:00:00 GMT-1000 (heure normale d’Hawaii - Aléoutiennes)

后:

> toDate("2020-10-06")
> Date Tue Oct 06 2020 12:00:00 GMT-1000 (heure normale d’Hawaii - Aléoutiennes)

我只是想就这个问题发表我的意见,因为这篇文章对解决这个问题非常有帮助。我想我没见过这个解决方案,如果我说错了请指正。

正如这里已经提到过无数次的那样,问题主要来自夏季/冬季时间。我注意到1月份的GMT是+1。如果没有设置时间,它将始终是00.00.00(午夜),这将导致前一天的第23小时。

如果您有一个动态日期并且不关心小时,您可以在使用toISOString()之前使用setHours()方法设置小时。

语法: setHours(hoursValue, minutesValue, secondsValue, msValue)

这意味着:

dynamicDate.setHours(12, 0, 0, 0)
dynamicDate.toISOString()

应该希望为您工作,即使日期提前/后一个小时,它仍然是同一天,现在我们将时间设置为中午。

更多关于MDN上的setHours()。