Skip to content

Commit

Permalink
fix(isDate): Timezone Offset Fix (#2257)
Browse files Browse the repository at this point in the history
* Timezone Offset Fix & Parsing with Leading Zeros

* `isDate` Timezone Mock Test, Support for NodeJS <8

* `isDate` Unit Test Resiliency Improvement
  • Loading branch information
tomaspanek authored Aug 18, 2023
1 parent f074abd commit 2c4aede
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"rimraf": "^3.0.0",
"rollup": "^0.47.0",
"rollup-plugin-babel": "^4.0.1",
"timezone-mock": "^1.3.6",
"uglify-js": "^3.0.19"
},
"scripts": {
Expand Down
14 changes: 13 additions & 1 deletion src/lib/isDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,19 @@ export default function isDate(input, options) {
}
}

return new Date(`${fullYear}-${dateObj.m}-${dateObj.d}`).getDate() === +dateObj.d;
let month = dateObj.m;

if (dateObj.m.length === 1) {
month = `0${dateObj.m}`;
}

let day = dateObj.d;

if (dateObj.d.length === 1) {
day = `0${dateObj.d}`;
}

return new Date(`${fullYear}-${month}-${day}T00:00:00.000Z`).getUTCDate() === +dateObj.d;
}

if (!options.strictMode) {
Expand Down
12 changes: 12 additions & 0 deletions test/validators.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import assert from 'assert';
import fs from 'fs';
import timezone_mock from 'timezone-mock';
import { format } from 'util';
import vm from 'vm';
import validator from '../src/index';
Expand Down Expand Up @@ -13054,6 +13055,17 @@ describe('Validators', () => {
'29.02.2020',
],
});
// emulating Pacific time zone offset & time
// which could potentially result in UTC conversion issues
timezone_mock.register('US/Pacific');
test({
validator: 'isDate',
valid: [
new Date(2016, 2, 29),
'2017-08-04',
],
});
timezone_mock.unregister();
});
it('should validate time', () => {
test({
Expand Down

0 comments on commit 2c4aede

Please sign in to comment.