A2oz

How to Log Date in Console JavaScript?

Published in JavaScript 2 mins read

To log the current date in the console using JavaScript, you can use the Date object and its methods. Here's how:

  1. Create a Date Object:

    const currentDate = new Date();
  2. Log the Date Object:

    console.log(currentDate); 

    This will output the current date and time in a format like: Mon Jul 10 2023 14:40:26 GMT-0400 (Eastern Daylight Time).

  3. Format the Date:
    You can format the date using the toLocaleDateString() method. For example, to get the date in MM/DD/YYYY format:

    console.log(currentDate.toLocaleDateString('en-US')); // Output: 07/10/2023

    You can use other locale codes to get different date formats.

  4. Log Specific Date Parts:
    You can access specific parts of the date using methods like getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), and getSeconds().

    console.log(`Today's date is ${currentDate.getDate()}/${currentDate.getMonth() + 1}/${currentDate.getFullYear()}`); // Output: Today's date is 10/7/2023
  5. Custom Formatting:
    You can create custom date formats using string templates and the padStart() method.

    const formattedDate = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')}`;
    console.log(formattedDate); // Output: 2023-07-10

By using these methods, you can log the current date in various formats and manipulate it as needed.

Related Articles