How to get exact currect time in javascript? For Example when you execute the code you whoud get (2016-02-11 03:11:22:33).
Note: There is so many tutorial but none of them gives you the milliseconds of current time.
This function
should do it :
function getTime(input) {
var date = input ? new Date(input) : new Date();
return {
hours : date.getHours(),
minutes : date.getMinutes(),
seconds : date.getSeconds(),
milliseconds : date.getMilliseconds()
}
}
If I would run getTime()
right now (20:52:49 200ms), I'd get an object with the following properties :
{
hours: 20,
minutes: 52,
seconds: 49,
milliseconds: 200
}
If you prefer your output to be a string instead of an object, you could also use this function :
var getTimeString = function(input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = input ? new Date(input) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds()),
date.getMilliseconds()
].join(typeof separator !== 'undefined' ? separator : ':' );
}
If I would run getTimeString()
right now (20:52:49 200ms), I'd get this string :
20:52:49:200
See also this Fiddle.