Reputation: 1369
I'm probably just tired and not thinking clearly, but can someone give a concise way of getting the number of milliseconds passed since the last minute using javascript?
Something like Date.getSeconds()
, but that would return milliseconds.
Although I could just do (Date.getSeconds()*1000) + Date.getMilliseconds()
, this just seems really awkward and like there has to be a better way.
Thanks!
Upvotes: 2
Views: 1199
Reputation: 3655
Depends what you're trying to do.
The difference between now and 1 minute ago in milliseconds should always be 60000 milliseconds. o_O
As Jan said Date.now()
will return the current timestamp in milliseconds.
But it seems you might be looking for the getTime method, e.g.: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTime
// note the keyword "new" below
var date_instance = new Date();
// separate example in case you're managing Date()'s and not the method,
// who knows, just an example
var timestamp = date_instance.getTime();
var minute_before_timestamp = function(ts){
return ts - 60000;
};
console.log(minute_before_timestamp(timestamp));
console.log(minute_before_timestamp(date_instance.getTime()); // always same as above!
// or use the current time
console.log(minute_before_timestamp(Date.now()));
console.log(minute_before_timestamp(new Date().getTime()));
(another useful link: http://www.epochconverter.com/)
Upvotes: 6
Reputation: 8368
What about…
Date.now() % 60000
Date.now
returns the current UNIX timestamp in ms.
To clarify what's happening there, the %
operator is called modulo and what it does is that it gives you the remainder from dividing the first number by the other one.
An example can be:
20 % 7 === 6
13 % 7 === 6
6 % 7 === 6
…because…
20 / 7 = 2 + 6 / 7
13 / 7 = 1 + 6 / 7
6 / 7 = 0 + 6 / 7
(note the remainder 6
)
Upvotes: 5