2012-10-09 78 views
22
var dateObj = new Date(); 
var val = dateObj.getTime(); 
//86400 * 1000 * 3 Each day is 86400 seconds 
var days = 259200000; 

val = val + days; 
dateObj.setMilliseconds(val); 
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear(); 
alert(val); 

我試圖把當前的日期,加上毫秒三天吧,3天后從當前具有日期戳顯示。例如 - 如果今天是2012年10月9日,那麼我想說它是2012年10月12日。試圖以毫秒爲單位增加3天當前日期

這種方法不工作,我得到了幾個月和幾天的方式。有什麼建議麼?

+1

我想你想時刻設定,而不是setMilliseconds –

+0

嘗試:'dateObj.setTime(dateObj.getTime()+ 8.64e7 * 3)'但注意夏令時更換可能會導致意想不到的結果。比較簡單,只需在日期中添加3:'dateObj.setDate(dateObj.getDate()+ 3)'。 – RobG

回答

38

要添加時間,得到當前的日期再加入,以毫秒爲單位,具體的時間量,然後創建一個新的日期值:

// get the current date & time 
var dateObj = Date.now(); 

// Add 3 days to the current date & time 
// I'd suggest using the calculated static value instead of doing inline math 
// I did it this way to simply show where the number came from 
dateObj += 1000 * 60 * 60 * 24 * 3; 

// create a new Date object, using the adjusted time 
dateObj = new Date(dateObj); 

爲了進一步解釋這一點,原因dataObj.setMilliseconds()不起作用是因爲它將dateobj的毫秒PROPERTY設置爲指定的值(介於0和999之間的值)。它不會將對象的日期設置爲毫秒。

// assume this returns a date where milliseconds is 0 
dateObj = new Date(); 

dateObj.setMilliseconds(5); 
console.log(dateObj.getMilliseconds()); // 5 

// due to the set value being over 999, the engine assumes 0 
dateObj.setMilliseconds(5000); 
console.log(dateObj.getMilliseconds()); // 0 
+1

我只是變種天= 259200000,因爲它是靜態的,永遠不會改變。謝謝!好奇,爲什麼沒有設置Milliseconds(天)做同樣的事情? – dman

+1

我真的不知道。我剛從的experiance知道這是否是靜態值,然後執行計算出像以上。 – SReject

+4

由於這是(一年後)拿出添加毫秒到日後的第一個項目,原因setMilliseconds不起作用是它設置Date對象的毫秒部分。因此,在正常操作中,它期望從0-999的數字。然而,它允許任何數目的,並且是如添加的值的日期不帶日期的前一毫秒組件。 –

3

如果需要製造日期計算在JavaScript中,使用moment.js

moment().add('days', 3).calendar(); 
+7

對你沒有任何意義,但建議使用整個庫來完成這樣一個簡單的任務似乎完全是這樣做的。 – SReject

+5

沒有冒犯,當其他人閱讀我的代碼時,他可能會比接受的答案更好地理解moment.js一行。 –

+2

這個任務沒有什麼「簡單」。考慮夏時制的變化。 –

4

試試這個:

var dateObj = new Date(Date.now() + 86400000 * 3);

3

使用此代碼

var dateObj = new Date(); 
var val = dateObj.getTime(); 
//86400 * 1000 * 3 Each day is 86400 seconds 
var days = 259200000; 

val = val + days; 
dateObj = new Date(val); // ********important*********// 
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear(); 
alert(val); 
相關問題