Languages
[Edit]
EN

How to get current time in JavaScript?

4 points
Created by:
AnnLen
1780

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.