0

我的项目中有一个奇怪的问题。我正在尝试将参数动态插入到 Date 对象构造函数中。这是我的代码:

from += fromYear + "," + fromMonth + "," + fromDay + "," + fromHour + "," + fromMinute;
to += toYear + "," + toMonth + "," + toDay + "," + toHour + "," + toMinute;

console.log(from);  //here is log value: 2012,8,25,9,22
console.log(to);   //another log: 2012,8,25,9,52

//Creating object               
var fromtime =  new Date(from);
var totime = new Date(to);

当我试图提醒日期对象(totime 或 fromtime)时,出现错误:Invalid Date。我不知道如何通过它。你可以帮帮我吗?

我试过这个: 创建日期对象 JS

4

3 回答 3

2

在您的示例from中是一个逗号分隔的字符串,而不是一系列谨慎的变量,这是Date构造函数需要作为参数的:

var fromtime =  new Date(fromYear, fromMonth, fromDay, fromHour, fromMinute);

(月份以 0 为基础,因此您可能需要添加 1)

于 2012-09-25T09:45:00.773 回答
1

如果您以以下格式创建日期

new Date(year, month, day, hours, minutes, seconds, milliseconds)

您应该直接传递参数而不是连接它们,就像这样

new Date(fromYear, fromMonth, fromDay, fromHour, fromMinute, 0)
于 2012-09-25T09:44:43.297 回答
0

What you are doing is

var fromtime = new Date('2012,8,25,9,22');
instead of
var fromtime = new Date(2012,8,25,9,22);

What you need to do is use the dates you have and if it's in a string weed out the diffrent parts of the date

new Date(fromYear, fromMonth, fromDay, fromHour, fromMinute, 0)

I don't think JS will allow you to do that.
You give it one parameter instead of the five you intend.

http://www.w3schools.com/js/js_obj_date.asp

于 2012-09-25T10:03:52.927 回答