Skip to content

Commit

Permalink
Merge pull request #444 from chriso/chriso/isDate-timezone-fix
Browse files Browse the repository at this point in the history
Fix isDate() handling of ISO8601 timezones
  • Loading branch information
chriso committed Oct 20, 2015
2 parents 902cfc9 + bec6583 commit 351b8c3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#### HEAD

- Fix `isDate()` handling of ISO8601 timezones
([#444](https://github.com/chriso/validator.js/pull/444))
- Fix the incorrect `isFloat('.') === true`
([#443](https://github.com/chriso/validator.js/pull/443))
- Added a Norwegian locale to `isMobilePhone()`
Expand Down
5 changes: 5 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -889,6 +889,11 @@ describe('Validators', function () {
, '2009-05-19 14:39:22-06:00'
, '2009-05-19 14:39:22+0600'
, '2009-05-19 14:39:22-01'
, '2015-10-20T00:53:09+08:00'
, '2015-10-20T00:53:09+09:00'
, '2015-10-20T00:53:09+10:00'
, '2015-10-20T00:53:09+11:00'
, '2015-10-20T00:53:09+12:00'
, '2007-04-06T00:00'
, '2010-02-18T16:23:48.5'
, '200905'
Expand Down
29 changes: 28 additions & 1 deletion validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -470,10 +470,37 @@
return pattern && pattern.test(str);
};

function getTimezoneOffset(str) {
var iso8601Parts = str.match(iso8601);
if (!iso8601Parts) {
return new Date().getTimezoneOffset();
}
var timezone = iso8601Parts[21];
if (!timezone || timezone === 'z' || timezone === 'Z') {
return 0;
}
var sign = iso8601Parts[22], hours, minutes;
if (timezone.indexOf(':') !== -1) {
hours = parseInt(iso8601Parts[23]);
minutes = parseInt(iso8601Parts[24]);
} else {
hours = 0;
minutes = parseInt(iso8601Parts[23]);
}
return (hours * 60 + minutes) * (sign === '-' ? 1 : -1);
}

validator.isDate = function (str) {
var normalizedDate = new Date((new Date(str)).toUTCString());
var regularDay = String(normalizedDate.getDate());
var utcDay = String(normalizedDate.getUTCDate());
// normalizedDate is in the user's timezone. Apply the input
// timezone offset to the date so that the year and day match
// the input
var timezoneDifference = normalizedDate.getTimezoneOffset() -
getTimezoneOffset(str);
normalizedDate = new Date(normalizedDate.getTime() +
60000 * timezoneDifference);
var regularDay = String(normalizedDate.getDate());
var dayOrYear, dayOrYearMatches, year;
if (isNaN(Date.parse(normalizedDate))) {
return false;
Expand Down
Loading

0 comments on commit 351b8c3

Please sign in to comment.