1

我使用以下脚本在一个字段中输入日期,向其中添加天数以填充另一个字段。现在我想做相反的事情,输入日期并减去天数以填充不同的字段。

//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));`
4

2 回答 2

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)

以类似的方式,您可以添加或减去月份和年份、小时或分钟。

于 2013-07-10T18:57:36.263 回答
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;
于 2013-07-10T18:50:24.143 回答