Languages
[Edit]
EN

How to get current time in JavaScript?

4 points
Created by:
AnnLen
9180

In JavaScript to get current time Date class is useful.

Quick solution:

// ONLINE-RUNNER:browser;

var now = Date.now();

console.log('Current unix millisecond time: ' + now);

1. Predefined methods example

// ONLINE-RUNNER:browser;

var now = new Date();

console.log('Current unix millisecond time: ' + now.getTime());
console.log('Current date: ' + now.toDateString());
console.log('Current time: ' + now.toTimeString());
console.log('Current date & time: ' + now.toString());

Note: during using to...String methods it is necessaryto be careful because of specific formatting of data and time on the locale.

2. Custom formatting (year, month, day, hour, minute, second, ...) example

// ONLINE-RUNNER:browser;

function renderNumber(value, length) {
    var result = String(value);
    for(; length > result.length; length -= 1) {
        result = '0' + result;
    }
    return result;
}

function renderDate(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    var text = renderNumber(year, 4) 
        + '.' + renderNumber(month, 2) 
        + '.' + renderNumber(day, 2);
    return text;
}

function renderTime(date) {
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var millisecond = date.getMilliseconds();

    var text = renderNumber(hour, 2) 
        + ':' + renderNumber(minute, 2) 
        + ':' + renderNumber(second, 2) 
        + '.' + renderNumber(millisecond, 3);
    return text;
}

function renderDateTime(date) {
    var dateText = renderDate(date);
    var timeText = renderTime(date);
  
    return dateText + ' ' + timeText;
}

// Usage example:

var now = new Date();

var date = renderDate(now);
var time = renderTime(now);
var dateTime = renderDateTime(now);

console.log('Current date: ' + date);
console.log('Current time: ' + time);
console.log('Current date & time: ' + dateTime);

References

  1. Date class - MDC Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join