How to Get Date and Time from Date Object in JavaScript

// Get the current date and time
const currentDate = new Date();

// Extract the year, month, and date from the current date
const year = currentDate.getFullYear();
const month = (currentDate.getMonth() + 1).toString().padStart(2, "0"); // Month is zero-based, so add 1
const date = currentDate.getDate().toString().padStart(2, "0"); // Pad with leading zero if necessary

// Combine year, month, and date to form the local date string
const localDate = `${year}-${month}-${date}`;

// Extract the hours, minutes, and seconds from the current date
const hours = currentDate.getHours().toString().padStart(2, "0");
const minutes = currentDate.getMinutes().toString().padStart(2, "0");
const seconds = currentDate.getSeconds().toString().padStart(2, "0");

// Combine hours, minutes, and seconds to form the local time string
const localTime = `${hours}:${minutes}:${seconds}`;

// Output the local date and time
console.log("Local Date:", localDate);
console.log("Local Time:", localTime);

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda