#javascript
#webdevelopment
#get current date & time

Get Current Date and Time Using JS

Anonymous

AnonymousJan 03, 2024

To get the current date and time using JavaScript, you can use Date object() and formats it using the toLocaleTimeString() and toLocaleDateString() methods to get the current time and date in a human-readable format. The dayOfWeek, formattedDate, and formattedTime variables are then used to store the formatted date and time values.

Here is an example of JavaScript code that get the current date and time:

document.addEventListener('DOMContentLoaded', function () {
  const dateTimeElement = document.getElementById('datetime');

  function updateDateTime() {
    const currentDate = new Date();
    const options = { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true };
    const formattedTime = currentDate.toLocaleTimeString('en-US', options);

    const dayOfWeek = new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(currentDate);
    const formattedDate = currentDate.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });

    console.log(`Today is :  ${dayOfWeek}\n\nCurrent Date is : ${formattedDate}\n\nCurrent Time is : ${formattedTime}`);
  }
  updateDateTime(); // Initial call
  setInterval(updateDateTime, 1000); // Update every second
});

Output:

Today is: Thursday

Current Date is: 4 January 2024

Current Time is: 4: 29: 22 PM

Happy Coding! ❤️