Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

How to get current time in JavaScript?

0 contributions
4 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more