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

当前回答

这解决了我的问题(感谢@Sebastiao的回答)

var date = new Date();
//"Thu Jun 10 2021 18:46:00 GMT+0200 (Eastern European Standard Time)"

date.toString().split(/\+|-/)[0] ;  // .split(/\+|-/) is a regex for matching + or -
//"Thu Jun 10 2021 18:46:00 GMT"

var date_string_as_Y_M_D = (new Date(date)).toISOString().split('T')[0];
//2021-06-10

其他回答

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

我的应用程序是全球使用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是我想要的。希望这对一些人有所帮助。

我解析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)

由于大多数答案都很俗气,请允许我提出对我来说非常简单的方法:将脚本的时区设置为UTC

process.env.TZ = 'UTC' // this has to be run before any use of dates

有了这个更改,任何时区修改都是无效的,所以只要您不需要跑步者的实际时区,这可能是最简单的解决方法。

这解决了我的问题(感谢@Sebastiao的回答)

var date = new Date();
//"Thu Jun 10 2021 18:46:00 GMT+0200 (Eastern European Standard Time)"

date.toString().split(/\+|-/)[0] ;  // .split(/\+|-/) is a regex for matching + or -
//"Thu Jun 10 2021 18:46:00 GMT"

var date_string_as_Y_M_D = (new Date(date)).toISOString().split('T')[0];
//2021-06-10

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