在我的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)
在我的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)
当前回答
如果你需要一个简单的解决方案,请参阅:
new Date('1993-01-20'.split('-'));
其他回答
这个通过我循环,zzzBov的答案是+1。这是一个完整的转换日期,为我工作使用UTC方法:
//myMeeting.MeetingDate = '2015-01-30T00:00:00'
var myDate = new Date(myMeeting.MeetingDate);
//convert to JavaScript date format
//returns date of 'Thu Jan 29 2015 19:00:00 GMT-0500 (Eastern Standard Time)' <-- One Day Off!
myDate = new Date(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate());
//returns date of 'Fri Jan 30 2015 00:00:00 GMT-0500 (Eastern Standard Time)' <-- Correct Date!
// 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"
下面的方法对我很有效
var doo = new Date("2011-09-24").format("m/d/yyyy");
遵循代码对我很有效。首先,我将日期和时间字符串转换为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.
意思是格林尼治时间2011-09-24 00:00:00,因为你现在在格林尼治时间-4,所以是前一天的20:00。
就我个人而言,我得到的是2011-09-24 02:00:00,因为我生活在GMT +2。