2013-07-10 95 views
1

我已經使用以下腳本在一個字段中輸入日期,爲其添加日期以填充另一個字段。現在我想做相反的事情,輸入日期並減去天數來填充不同的字段。使用parseInt減去日期

//Script below is the addition 
//Field: CTS D/R 

var dString = getField("Task Anlys").value; 
var dParts = dString.split("-"); 

var mydate=new Date(); 

mydate.setDate(dParts[0]); 
mydate.setMonth(monthsByName[dParts[1]]); 
mydate.setYear(dParts[2]); 

//Date + 14 Days * 24 Hours * 60 Minutes * 60 Seconds * 1000 milliseconds 
var calNewDays = 14 * 24 * 60 * 60 * 1000; 

//Set new date 
mydate.setTime(calNewDays + parseInt(mydate.getTime())); 

var year=mydate.getYear() + 1900; 
var month=mydate.getMonth(); 
var day=mydate.getDate(); 

getField("CTS D/R").value = day + "-" + months[month] + "-" + year;` 

//Script below is an attempt for subtraction 

//Date = 30 Days * 24 Hours * 60 Minutes * 60 Seconds * 1000 milliseconds 
var calNewDays = 30 * 24 * 60 * 60 * 1000; 

//Set new date 
mydate.setTime(parseInt(mydate.getTime() - calNewDays));` 
+0

什麼問題? –

+0

我建議查找date.js腳本。它有各種方便的日期功能。 –

+2

處理日期時,最好使用像[Moment.js](http://momentjs.com/)這樣的庫, –

回答

0

爲什麼不加/減上設定的日期部分,這樣的天所需量?

var dString = getField("Task Anlys").value; 
var dParts = dString.split("-"); 
var oldDate = dParts[0] * 1; // convert to number 

var mydate=new Date(); 
mydate.setDate(oldDate + 14); // Date object automagically does all calendar math 
mydate.setMonth(monthsByName[dParts[1]]); 
mydate.setFullYear(dParts[2]); 

var year=mydate.getFullYear(); 
var month=mydate.getMonth(); 
var day=mydate.getDate(); 

getField("CTS D/R").value = day + "-" + months[month] + "-" + year; 
1

JavaScript Date對象可以非常簡單地完成所有您需要的數據運算。 :

var d = new Date(); // a date 
d.setDate (d.getDate() + 5); // add 5 days to d 
           // doing month and year overflow as necessary 

d.setDate (d.getDate() - 5); // subtract 5 days from d 
           // doing month and year overflow as necessary 


var d = new Date();   // ==> Wed Jul 10 2013 20:55:53 GMT+0200 (CEST) 
d.setDate (d.getDate() + 33); // ==> Mon Aug 12 2013 20:52:15 GMT+0200 (CEST) 

var d = new Date();   // ==> Wed Jul 10 2013 20:55:53 GMT+0200 (CEST) 
d.setDate (d.getDate() - 15) // ==> Tue Jun 25 2013 20:52:47 GMT+0200 (CEST) 

以類似的方式,您可以添加或減去月份和年份,小時或分鐘。