Skip to content

Commit 4f39196

Browse files
fix: parsing date formats with leading and trailing spaces
1 parent 8779a7c commit 4f39196

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/dates/parse-date.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ const numberRegExp = {
1818
const numberRegex = /\d+/;
1919
const PLACEHOLDER = "{0}";
2020

21+
const leadingSpacesRegex = /^ +/;
22+
const trailingSpacesRegex = / +$/;
23+
2124
const standardDateFormats = [
2225
"yyyy/MM/dd HH:mm:ss",
2326
"yyyy/MM/dd HH:mm",
@@ -456,13 +459,20 @@ function createDate(state) {
456459
return result;
457460
}
458461

462+
function addFormatSpaces(value, format) {
463+
const leadingSpaces = (leadingSpacesRegex.exec(format) || [])[0] || '';
464+
const trailingSpaces = (trailingSpacesRegex.exec(format) || [])[0] || '';
465+
466+
return `${ leadingSpaces }${ value }${ trailingSpaces }`;
467+
}
468+
459469
function parseExact(value, format, info) {
460470
let pattern = datePattern(format, info).split(EMPTY);
461471

462472
const state = {
463473
format: pattern,
464474
idx: 0,
465-
value: value,
475+
value: addFormatSpaces(value, format),
466476
valueIdx: 0,
467477
year: null,
468478
month: null,

test/dates.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,11 @@ describe('date parsing', () => {
459459
expect(parseDate("12/23/29", "M/d/yy").getFullYear(), 2029);
460460
});
461461

462+
it('prases formats with leading and trailing spaces', function () {
463+
const result = parseDate(" 12/23/2000 ", " MM/dd/yyyy ");
464+
expect(isValidDate(2000, 12, 23, result)).toBe(true);
465+
});
466+
462467
it('prases G format time', function () {
463468
const result = parseDate("12/23/2000 8:12:22 pm", "G");
464469
expect(isValidDateTime(result, 2000, 12, 23, 20, 12, 22)).toBe(true);

0 commit comments

Comments
 (0)