基于 PDF 表单中的独立表单字段计算日期

时间:2021-01-22 14:00:29

标签: javascript forms date acrobat

我想计算一个日期,该日期正好比在 PDF 表单的单独日期字段中选择的日期早 5 天。例如,如果我在 Date1 中选择“2021 年 7 月 10 日”,我希望 Date2 自动填充“2021 年 7 月 5 日”。

我知道如何从字段 1 中获取日期并用它填充字段 2,并且我知道如何进行 5 天(前)计算。我真正挣扎的部分是将这两件事放在文档中。如果我想从当前日期计算 5 天前,我可以做到这一点,因为它在整个地球和互联网上都有记录,哈哈。但是从另一个字段中的选定日期计算 5 天前让我陷入困境。

我不精通 JavaScript,但我也想知道这是否可能是一个解决方案:

//turning this piece of code    
event.value=this.getField("Date1").value;

//into this piece of code
var d = this.getField("Date1").value;

由于我不需要第二个日期字段来实际填充第一个日期字段值,我想知道是否像将第一个字段值转换为变量然后将变量放入计算脚本中一样简单表单字段属性中的“自定义计算脚本”。

1 个答案:

答案 0 :(得分:0)

虽然我无法帮助您设置/获取 PDF 表单项,以下是如何使用您的日期字符串格式“MMM DD, YYYY”在 JavaScript 中从日期中添加或减去天数:

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];

// convert "MMM, DD, YYYY" string to Date object
function makeDateFromStr(str) {
  const strNoComma = str.split(',').join('');
  const [monthStr, day, year] = strNoComma.split(' ');
  const monthIndex = months.indexOf(monthStr);
  return new Date(year, monthIndex, day);
}

// add/subtract number of days to Date object,
// returning new date
function addDaysToDate(date, addDays) {
  const currDays = date.getDate();
  const newDate = new Date(date.getTime());
  newDate.setDate(currDays + addDays);
  return newDate;
}

// convert Date object to string "MMM DD, YYYY"
function myDateFormat(date) {
  const monthStr = months[date.getMonth()];
  const day = date.getDate();
  const year = date.getFullYear();
  return `${monthStr} ${day}, ${year}`;
}

const date1Str = "Jul 10, 2011";
console.log(`date1Str: "${date1Str}"`);

const date1 = makeDateFromStr(date1Str);
console.log('date1:',date1.toISOString());

const date2 = addDaysToDate(date1, -5);
console.log('date2:',date2.toISOString());

const date2Str = myDateFormat(date2);
console.log(`date2Str: "${date2Str}"`);

相关问题