Skip to content

Commit 351b8c3

Browse files
committed
Merge pull request #444 from chriso/chriso/isDate-timezone-fix
Fix isDate() handling of ISO8601 timezones
2 parents 902cfc9 + bec6583 commit 351b8c3

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#### HEAD
22

3+
- Fix `isDate()` handling of ISO8601 timezones
4+
([#444](https://github.com/chriso/validator.js/pull/444))
35
- Fix the incorrect `isFloat('.') === true`
46
([#443](https://github.com/chriso/validator.js/pull/443))
57
- Added a Norwegian locale to `isMobilePhone()`

test/validators.js

+5
Original file line numberDiff line numberDiff line change
@@ -889,6 +889,11 @@ describe('Validators', function () {
889889
, '2009-05-19 14:39:22-06:00'
890890
, '2009-05-19 14:39:22+0600'
891891
, '2009-05-19 14:39:22-01'
892+
, '2015-10-20T00:53:09+08:00'
893+
, '2015-10-20T00:53:09+09:00'
894+
, '2015-10-20T00:53:09+10:00'
895+
, '2015-10-20T00:53:09+11:00'
896+
, '2015-10-20T00:53:09+12:00'
892897
, '2007-04-06T00:00'
893898
, '2010-02-18T16:23:48.5'
894899
, '200905'

validator.js

+28-1
Original file line numberDiff line numberDiff line change
@@ -470,10 +470,37 @@
470470
return pattern && pattern.test(str);
471471
};
472472

473+
function getTimezoneOffset(str) {
474+
var iso8601Parts = str.match(iso8601);
475+
if (!iso8601Parts) {
476+
return new Date().getTimezoneOffset();
477+
}
478+
var timezone = iso8601Parts[21];
479+
if (!timezone || timezone === 'z' || timezone === 'Z') {
480+
return 0;
481+
}
482+
var sign = iso8601Parts[22], hours, minutes;
483+
if (timezone.indexOf(':') !== -1) {
484+
hours = parseInt(iso8601Parts[23]);
485+
minutes = parseInt(iso8601Parts[24]);
486+
} else {
487+
hours = 0;
488+
minutes = parseInt(iso8601Parts[23]);
489+
}
490+
return (hours * 60 + minutes) * (sign === '-' ? 1 : -1);
491+
}
492+
473493
validator.isDate = function (str) {
474494
var normalizedDate = new Date((new Date(str)).toUTCString());
475-
var regularDay = String(normalizedDate.getDate());
476495
var utcDay = String(normalizedDate.getUTCDate());
496+
// normalizedDate is in the user's timezone. Apply the input
497+
// timezone offset to the date so that the year and day match
498+
// the input
499+
var timezoneDifference = normalizedDate.getTimezoneOffset() -
500+
getTimezoneOffset(str);
501+
normalizedDate = new Date(normalizedDate.getTime() +
502+
60000 * timezoneDifference);
503+
var regularDay = String(normalizedDate.getDate());
477504
var dayOrYear, dayOrYearMatches, year;
478505
if (isNaN(Date.parse(normalizedDate))) {
479506
return false;

0 commit comments

Comments
 (0)