Skip to content

Instantly share code, notes, and snippets.

@RubaXa
Created July 14, 2014 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RubaXa/ba292523e2fa11dab47e to your computer and use it in GitHub Desktop.
Save RubaXa/ba292523e2fa11dab47e to your computer and use it in GitHub Desktop.
Get current timestamp + offset
/**
* @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;
})();
@RubaXa
Copy link
Author

RubaXa commented Jul 14, 2014

now("+year");
now("+3 months");
now("-13 min");
now("+86400 ms")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment