简体   繁体   中英

get exact time in javascript

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 .

Extending John's idea, you can add configuration options to your getTime function such as whether the time is 24 hours and if it is UTC.

 var now = new Date(); document.body.innerHTML = 'Local: ' + format(getTime(now, true, false)) + '\\n'; document.body.innerHTML += 'UTC: ' + format(getTime(now, true, true)); /** * Returns an object with time information for a given Date object.<p> * @param date {Date} A date object used to retrieve information. * @return Returns an object containg hours, minutes, seconds, * and milliseconds for the supplied date. */ function getTime(date, is24Hour, isUTC) { var hour = isUTC ? date.getUTCHours() : date.getHours(); var meridiem = hour < 12 ? 'AM' : 'PM'; hour = is24Hour ? hour % 12 : hour; hour = hour === 0 ? 12 : hour; var data = { hours : hour, minutes : isUTC ? date.getUTCMinutes() : date.getMinutes(), seconds : isUTC ? date.getUTCSeconds() : date.getSeconds(), milliseconds : isUTC ? date.getUTCMilliseconds() : date.getMilliseconds(), is24Hour : is24Hour, isUTC : isUTC }; if (is24Hour) { data.meridiem = meridiem; } return data; } function format(time) { function pad(val, str) { return ('' + str + val).substr(-str.length); } return pad(time.hours, '00') + ':' + pad(time.minutes, '00') + ':' + pad(time.seconds, '00') + '.' + pad(time.milliseconds, '000') + ' ' + time.meridiem || ''; } 
 body { white-space: pre; font-family: monospace; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM