Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get current time in JavaScript

Learning how to get the current time in JavaScript is an essential skill for new programmers, as it opens up a world of possibilities in terms of creating interactive and dynamic web applications. Time is a fundamental aspect of many applications, such as clocks, timers, or any feature that relies on scheduling events.

In this blog post, we will learn how to get the current time in JavaScript. We will cover the following topics:

  1. Introducing the Date object
  2. Getting the current date and time
  3. Extracting specific time units like hours, minutes, and seconds
  4. Formatting the time output
  5. Using third-party libraries for advanced time manipulation

1. Introducing the Date object

In JavaScript, the Date object is the go-to solution for working with dates and times. It provides methods and properties that allow you to perform various operations, such as:

  • Getting and setting date and time values
  • Formatting dates and times
  • Parsing date strings
  • Performing calculations with dates and times

To create a new Date object, you simply call the Date constructor like this:

const currentDate = new Date();

This will create a new Date object that represents the current date and time. The Date object stores the date and time as the number of milliseconds since January 1, 1970, 00:00:00 UTC, which is known as the Unix Epoch. The Unix Epoch is a common reference point used by many programming languages and systems to represent time.

Now that we have a basic understanding of the Date object, let's see how to use it to get the current date and time.

2. Getting the current date and time

As we've seen earlier, creating a new Date object with no arguments will give us an object representing the current date and time. To display this information, we can use the toString() method, which converts the Date object into a human-readable string:

const currentDate = new Date();
console.log(currentDate.toString());

Running this code will output something like this:

"Tue Sep 28 2021 12:34:56 GMT-0700 (Pacific Daylight Time)"

This output shows the current date and time, including the timezone information (in this case, Pacific Daylight Time). However, it might not be the most convenient format if you are only interested in the time portion. In the next section, we will learn how to extract specific time units like hours, minutes, and seconds.

3. Extracting specific time units

The Date object provides several methods that allow you to extract specific time units from a date and time value. Here are some of the most commonly used methods:

  • getHours(): Returns the hour (0-23) of the specified date and time.
  • getMinutes(): Returns the minutes (0-59) of the specified date and time.
  • getSeconds(): Returns the seconds (0-59) of the specified date and time.

Let's see how we can use these methods to display the current time:

const currentDate = new Date();
const currentHour = currentDate.getHours();
const currentMinute = currentDate.getMinutes();
const currentSecond = currentDate.getSeconds();

console.log(`${currentHour}:${currentMinute}:${currentSecond}`);

Running this code will output the current time in the following format:

12:34:56

This format is more suitable if you only need to display the time without the date or timezone information.

4. Formatting the time output

The previous example showed how to display the current time in a simple format. However, you might want to customize the appearance of the time output depending on your needs. For example, you may want to display leading zeros for single-digit hours, minutes, or seconds.

To achieve this, we can create a helper function that takes a number and returns a string with a leading zero if the number is less than 10:

function padZero(number) {
  return number < 10 ? '0' + number : number.toString();
}

Using this helper function, we can now update our previous example to display leading zeros:

const currentDate = new Date();
const currentHour = padZero(currentDate.getHours());
const currentMinute = padZero(currentDate.getMinutes());
const currentSecond = padZero(currentDate.getSeconds());

console.log(`${currentHour}:${currentMinute}:${currentSecond}`);

Running this code will output the current time with leading zeros:

12:04:05

This format looks more professional and is easier to read, especially when dealing with single-digit numbers.

5. Using third-party libraries for advanced time manipulation

While the built-in Date object provides basic functionality for working with dates and times, you might need more advanced features for certain applications. In such cases, you can use third-party libraries like Moment.js or date-fns that offer more powerful and flexible options for manipulating dates and times.

For example, using Moment.js, you can easily format the current time like this:

const moment = require('moment');
const currentTime = moment().format('HH:mm:ss');
console.log(currentTime);

This code will output the current time with leading zeros, similar to our previous example. However, Moment.js offers many more formatting options, as well as additional features like parsing, manipulating, and computing the difference between dates and times.

In conclusion, learning how to get the current time in JavaScript is an important step for beginners, as it opens up many possibilities for creating dynamic, time-based applications. By understanding how to use the Date object and its methods, you can create custom time formats, extract specific time units, and even use third-party libraries for advanced time manipulation. Happy coding!