首页 > javascript > 新日期不能给我正确的时间

新日期不能给我正确的时间 (new Date can't give me right time)

问题

startDate = "2019-03-07 (목) 12:00";

var year = startDate.slice(0,4);
var month = startDate.slice(5,7);
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);

var selEndDatetime = new Date(year, month, day, hour, minute);
console.log(selEndDatetime);

我希望看到“Tue Mar 07 2019 12:00:00 GMT + 0900(한국표준시)”,但是控制台向我显示消息“Sun Apr 07 2019 12:00:00 GMT + 0900(한국표준시)”。

这段代码有什么问题,如何修改它以获得所需的输出?

解决方法

月份从0开始。您需要在创建日期实例时将字符串从字符串解析为整数并减去1。

startDate = "2019-03-07 (목) 12:00";

var year = startDate.slice(0,4);
var month = parseInt(startDate.slice(5,7))
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);

var selEndDatetime = new Date(year, month - 1, day, hour, minute);
console.log(selEndDatetime);


问题

startDate = "2019-03-07 (목) 12:00";

var year = startDate.slice(0,4);
var month = startDate.slice(5,7);
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);

var selEndDatetime = new Date(year, month, day, hour, minute);
console.log(selEndDatetime);

I want to see "Tue Mar 07 2019 12:00:00 GMT+0900 (한국 표준시)", but console shows me the message "Sun Apr 07 2019 12:00:00 GMT+0900 (한국 표준시)".

What is wrong this code and how can I modify it to get the desired output?

解决方法

The month starts at 0. You need to parse month from string to integer and minus 1 when creating a date instance.

startDate = "2019-03-07 (목) 12:00";

var year = startDate.slice(0,4);
var month = parseInt(startDate.slice(5,7))
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);

var selEndDatetime = new Date(year, month - 1, day, hour, minute);
console.log(selEndDatetime);

相似信息