Created
July 14, 2014 10:59
-
-
Save RubaXa/ba292523e2fa11dab47e to your computer and use it in GitHub Desktop.
Get current timestamp + offset
This file contains 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
/** | |
* @desc now("+year"), now("+3 months"), now("-13 min") or now("+86400 ms") | |
*/ | |
(function () { | |
var R_ADD = /(?:([+-]?)\s*(\d*))\s*(year|month|day|hour|min|sec|ms)/; | |
var _getTime = Date.now || function () { return (new Date).getTime(); }, | |
_cache = {}, | |
_map = { | |
'year': 'FullYear', | |
'month': 'Month', | |
'day': 'Date', | |
'hour': 'Hours', | |
'min': 'Minutes', | |
'sec': 'Seconds', | |
'ms': 'Milliseconds' | |
} | |
; | |
function _add(method, x) { | |
x = parseInt(x, 10) || 0; | |
return function (date) { | |
date['set' + method](date['get' + method]() + x); | |
}; | |
} | |
/** | |
* Get current timestamp | |
* @param {String} [add] | |
* @returns {Number} | |
*/ | |
function now(add) { | |
if (add) { | |
var date, match; | |
if (_cache[add] === void 0) { | |
if (match = R_ADD.exec(add)) { | |
_cache[add] = _add(_map[match[3]], match[1] + match[2]); | |
} else { | |
return _getTime(); | |
} | |
} | |
date = new Date; | |
_cache[add](date); | |
return date.getTime(); | |
} | |
return _getTime(); | |
} | |
// Export | |
window.now = now; | |
})(); |
Author
RubaXa
commented
Jul 14, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment