2012-09-25 86 views
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)有一個錯誤:無效的日期。我不知道如何通過它。你可以幫幫我嗎?

我嘗試這樣做: Creating Date Object JS

回答

2

在你的例子中from是逗號分隔的字符串,而不是一系列謹慎的變量,它們是Date構造函數需要作爲參數:

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

(月份是基於0的,所以你可能需要添加1)

+0

沒錯。 +1指出0基地;) –

1

如果你正在創建中的

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

格式的日期,您應該直接傳遞的參數,而不是串聯它們,像這樣

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

你在做什麼是

VAR放在fromtime =新的日期(「2012,8, 25,9,22' );
而不是
var fromtime = new Date(2012,8,25,9,22);

你需要做的是使用你的日期,如果是在一個字符串淘汰的日期有多種不同的部分

新的日期(fromYear,fromMonth,fromDay,fromHour,fromMinute,0)

我不認爲JS會讓你這樣做。
你給它一個參數,而不是你想要的五個參數。

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

相關問題