Frequently, when writing time-related code, I write the following:
var SECONDS = 1000;
var MINUTES = 60 * SECONDS;
var HOURS = 60 * MINUTES;
var DAYS = 24 * HOURS;
(of course these are variables not constants, but they will never change, and I could make them un-changeable properties etc if I wanted to)
However I suspect these values already exist inside V8 / JavaScriptCore / Chakra and other JS engines.
However I suspect these values already exist inside V8 / JavaScriptCore / Chakra and other JS engines.
They are not exposed in any standard way. Language designers tend to expose a few things like Math.PI and Math.E which have to be approximated carefully to avoid errors in numerical code, but adding a bunch of universal constants for integers just bloats APIs and slows down interpreter startup.
If you would like to do this, you are better off (due to Node's require() peculiarities) defining a new module and write it as follows:
module.exports = {
seconds: 1000,
minutes: 60000,
hours: 3600000,
days: 86400000
}
This will allow to simply use require("yourmodulename").seconds and similar whenever required. The object will only be imported once.
One approach suggests something like this
module.exports = {
seconds: 1,
minutes: 60,
hours: 3600,
days: 86400
}
Usage might look something like this
// timestamps
var a = 123456;
var b = 300000;
// get number of hours
time = require("time");
var hours = Math.floor((b - a) / time.hours);
//=> 10
But I think you can do better. These time integers are useless outside of the context of the module. And it requires you to duplicate any logic or math in code that would reference these values. Starting to see why these values are not publicly exposed anywhere?
var time = {
minutes: 60,
hours: 3600,
days: 86400
};
module.exports = {
get: function get(interval, seconds) {
return Math.floor(seconds / time[interval]);
}
};
Notice we're not exporting the integers. Usage becomes something like
// timestamps
var a = 123456;
var b = 300000;
// get hours
time = require("time");
time.get("hours", b - a); // => 10
Much nicer, yeah?