From f0b549c2a2592654604b03ccb4a2c08e20563f93 Mon Sep 17 00:00:00 2001 From: Calixte Denizet Date: Sat, 19 Mar 2022 16:07:38 +0100 Subject: [PATCH] [JS] - Parse a date in using the given format first and then try the default date parser - it aims to fix #14672. --- src/scripting_api/aform.js | 19 +++++++++++-------- src/scripting_api/util.js | 10 +++++++--- test/unit/scripting_spec.js | 15 +++++++++++++++ 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/scripting_api/aform.js b/src/scripting_api/aform.js index 1994e28ad..1f3b0a155 100644 --- a/src/scripting_api/aform.js +++ b/src/scripting_api/aform.js @@ -53,16 +53,19 @@ class AForm { } _parseDate(cFormat, cDate) { - const ddate = Date.parse(cDate); - if (isNaN(ddate)) { - try { - return this._util.scand(cFormat, cDate); - } catch (error) { - return null; + let date = null; + try { + date = this._util.scand(cFormat, cDate); + } catch (error) {} + if (!date) { + date = Date.parse(cDate); + if (isNaN(date)) { + date = null; + } else { + date = new Date(date); } - } else { - return new Date(ddate); } + return date; } AFMergeChange(event = globalThis.event) { diff --git a/src/scripting_api/util.js b/src/scripting_api/util.js index 613d5fe93..6c8130ceb 100644 --- a/src/scripting_api/util.js +++ b/src/scripting_api/util.js @@ -373,6 +373,10 @@ class Util extends PDFObject { } scand(cFormat, cDate) { + if (typeof cDate !== "string") { + return new Date(cDate); + } + if (cDate === "") { return new Date(); } @@ -536,15 +540,15 @@ class Util extends PDFObject { const [re, actions] = this._scandCache.get(cFormat); - const matches = new RegExp(re, "g").exec(cDate); + const matches = new RegExp(`^${re}$`, "g").exec(cDate); if (!matches || matches.length !== actions.length + 1) { return null; } const data = { - year: 0, + year: 2000, month: 0, - day: 0, + day: 1, hours: 0, minutes: 0, seconds: 0, diff --git a/test/unit/scripting_spec.js b/test/unit/scripting_spec.js index c17a1ccd4..72af2150b 100644 --- a/test/unit/scripting_spec.js +++ b/test/unit/scripting_spec.js @@ -598,6 +598,21 @@ describe("Scripting", function () { }); }); + describe("AFParseDateEx", function () { + it("should parse a date with a format", async () => { + const check = async (date, format, expected) => { + const value = await myeval( + `AFParseDateEx("${date}", "${format}").toISOString()` + ); + expect(value).toEqual(new Date(expected).toISOString()); + }; + + await check("05", "dd", "2000/01/05"); + await check("12", "mm", "2000/12/01"); + await check("2022", "yyyy", "2022/01/01"); + }); + }); + describe("AFExtractNums", function () { it("should extract numbers", async () => { let value = await myeval(`AFExtractNums("123 456 789")`);