Last active
August 9, 2019 14:15
-
-
Save tadger/4572db07fa81f92d2cfd4bc4bedfeffd to your computer and use it in GitHub Desktop.
A frightening monkey-patch for the Safari Date constructor to construct dates using ISO strings without applying the timezone offset.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (w) { | |
// latest versions of Safari will have an Apple Pay object | |
if (!w.ApplePaySession) { | |
return; | |
} | |
var _Date = window.Date; | |
var unbind = Function.bind.bind(Function.bind); | |
function instantiate(constructor, args) { | |
return new (unbind(constructor, null).apply(null, args)); | |
} | |
w.Date = function(Date) { | |
NewDate.prototype = Date.prototype; | |
NewDate.now = Date.now; | |
NewDate.UTC = Date.UTC; | |
NewDate.parse = Date.parse; | |
return NewDate; | |
function NewDate() { | |
if (arguments.length === 1 && typeof arguments[0] === 'string') { | |
// validate ISO'ish formats that PestPac uses: | |
// `2000-01-01 12:34:56`, `2000-01-01T12:34:56`, `2000-01-01 12:34`, `2000-01-01T12:34` | |
var rgx = /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+)|(\d{4}-[01]\d-[0-3]\d[T| ]{1}[0-2]\d:[0-5]\d:[0-5]\d)$|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d)$/i; | |
var results = arguments[0].match(rgx); | |
if (results) { | |
// for testing: remove this line after testing | |
console.log('YAHTZEE!!'); | |
var dateString = results[0].replace(' ', 'T'); | |
var parts = dateString.toUpperCase().split('T'); | |
var datePart = parts[0]; | |
var timePart = parts[1]; | |
var datePieces = datePart.split('-'); | |
var timePieces = timePart.split(':'); | |
return new Date( | |
parseInt(datePieces[0]), | |
parseInt(datePieces[1]) - 1, // month is a zero-based index | |
parseInt(datePieces[2]), | |
parseInt(timePieces[0]), | |
parseInt(timePieces[1]), | |
parseInt(timePieces[2] || 0) | |
); | |
} | |
} | |
return instantiate(Date, arguments); | |
} | |
}(_Date); | |
}(window)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment