2017-02-15 35 views
0

嘗試將日期添加到日期值時,出現奇怪的輸出。Javascript setdate getDate()+ 28返回錯誤

var startdate = $("#JobStartDate").val(); 

startdate = new Date(startdate); 
startdate28 = startdate.setDate(startdate.getDate()+28); 

console.log(startdate); 
console.log(startdate28); 

結果

startdate = "Date 2017-03-15T00:00:00.000Z" 

startdate28 = 1489536000000 

任何想法,我要去的地方錯了嗎?

+0

'startdate.getDate()+ 28'將讓你以毫秒爲單位的時間+ 28 – Weedoze

+1

更確切地說,'setDate'返回毫秒,但還設置了日期* * – adeneo

+0

['setDate()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate)更改基礎日期對象然後返回自從01.01.1970 UTC – Andreas

回答

0

像這樣:

var startdate = $("#JobStartDate").val(); 

startdate = new Date(startdate); 
startdate28 = new Date(); 
startdate28.setDate(startdate.getDate()+28); 

console.log(startdate); 
console.log(startdate28); 
0

看一看下面的代碼片段:

var startdate = "2017-02-15"; 
 

 
startdate = new Date(startdate); 
 
startdate28 = new Date(); 
 
startdate28.setTime(startdate.getTime() + 28 * 86400000); 
 

 
console.log(startdate); 
 
console.log(startdate28);

請注意,您需要向我們setTime這一翻譯的setDate因爲這可能會導致當月份或年份與添加日期之前的日期不一致時出現錯誤。

結果將是:

「2017-02-15T00:00:00.000Z」

「2017-03-15T00:00:00.000Z」

0

爲這一行:startdate28 = startdate.setDate(startdate.getDate()+ 28); 您可以在「startdate28」中存儲從「startdate.setDate」返回的內容,並且此函數返回調整日期的時間戳。

你可以做的是創建一個新的Date對象的其他日期:以整數

var startdate = '2016-01-01'; 

startdate = new Date(startdate); 
startdate28 = new Date(startdate.setDate(startdate.getDate()+28)); 

console.log(startdate); 
console.log(startdate28); 
0

方法Date.getDate()的結果。所以,整數+28仍然是一個整數,而不是日期類型。嘗試:

var startdate; 
startdate = new Date("2017-03-15T00:00:00.000Z"); 
startdate28 = new Date(); 
startdate28.setDate(startdate.getDate()+28); 
console.log(startdate); 
console.log(startdate28); 
0

在這裏你去:

addDays = function(days) { 
    var startdate = new Date(this.valueOf()); 
    startdate.setDate(startdate.getDate() + days); 
    return startdate; 
} 

var startdate= new Date(); 

alert(dat.addDays(5))