A2oz

How to Log Current Time in JavaScript?

Published in JavaScript 2 mins read

You can log the current time in JavaScript using the Date object and its methods.

Getting the Current Time

  1. Create a Date object: This object represents the current date and time.

    const now = new Date();
  2. Use Date methods: The Date object offers methods to extract specific time components.

    • toLocaleString(): This method returns a string representing the current date and time in a localized format.

      console.log(now.toLocaleString()); // Example: "1/1/2024, 10:00:00 AM"
    • getHours(): This method returns the current hour (0-23).

      console.log(now.getHours()); // Example: 10
    • getMinutes(): This method returns the current minute (0-59).

      console.log(now.getMinutes()); // Example: 0
    • getSeconds(): This method returns the current second (0-59).

      console.log(now.getSeconds()); // Example: 0

Formatting the Time

You can format the time string according to your needs using string interpolation or methods like padStart().

const hours = now.getHours();
const minutes = now.getMinutes().toString().padStart(2, '0'); 
const seconds = now.getSeconds().toString().padStart(2, '0');

console.log(`${hours}:${minutes}:${seconds}`); // Example: 10:00:00

Logging to the Console

Finally, use console.log() to display the time in your browser's console.

console.log(`Current time: ${hours}:${minutes}:${seconds}`);

These methods allow you to log the current time in JavaScript in various formats and customize the output according to your requirements.

Related Articles