我使用以下脚本在一个字段中输入日期,为其添加天数以填充另一个字段。现在我想反过来,输入日期并减去天数以填充不同的字段。
//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 :(得分: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)
以类似的方式,您可以添加或减去月份,年份,小时或分钟。
答案 1 :(得分: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;