在我的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)

当前回答

如果希望获得本地时区某个日期的0小时,请将各个日期部分传递给date构造函数。

new Date(2011,08,24); // month value is 0 based, others are 1 based.

其他回答

遵循代码对我很有效。首先,我将日期和时间字符串转换为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.

我认为这与时区调整有关。您创建的日期是GMT,默认时间是午夜,但您的时区是EDT,因此减去4小时。试着验证一下:

var doo = new Date("2011-09-25 EDT");

这可能不是一个好的答案,但我只是想分享我在这个问题上的经验。

我的应用程序是全球使用utc日期的格式'YYYY-MM-DD',而datepicker插件我只接受js日期,这对我来说很难同时考虑utc和js。所以当我想传递一个'YYYY-MM-DD'格式的日期到我的datepicker,我首先转换为'MM/DD/YYYY'格式使用moment.js或任何你喜欢的,日期显示在datepicker现在是正确的。举个例子

var d = new Date('2011-09-24'); // d will be 'Fri Sep 23 2011 20:00:00 GMT-0400 (EDT)' for my lacale
var d1 = new Date('09/24/2011'); // d1 will be 'Sat Sep 24 2011 00:00:00 GMT-0400 (EDT)' for my lacale

显然d1是我想要的。希望这对一些人有所帮助。

// 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"

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

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