Explain Codes LogoExplain Codes Logo

How do I get the current time only in JavaScript

javascript
time-manipulation
date-object
local-time
Anton ShumikhinbyAnton Shumikhin·Sep 9, 2024
TLDR

Snap the current time in JavaScript with:

const time = new Date().toLocaleTimeString(); console.log(time); // "2:35:07 PM", unless you're a time-traveler

This one-liner will spill into the console the current time pegged to your system's locale.

Current Time Extraction Strategies

Getting the time components

Every hour, minute, and second from the current time is accessible through Date object methods:

const now = new Date(); const hours = now.getHours(); // Bid adieu to the 24h clock confusion const minutes = now.getMinutes(); // Gives you the current minute, not the next const seconds = now.getSeconds(); // Seconds, but remember, time flies!

Time formatted as "hh:mm"

Do you fancy a clean hh:mm format for your timepickers down to the last padded zero? Here you go:

const formattedTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0'); console.log(formattedTime); // "02:35", Simple, isn't it?

Local and 24-hour time stamps

With toLocaleTimeString, you can switch between the 24-hour format or adopt the local time preferences like a true citizen of the world:

const options = { hour: '2-digit', minute: '2-digit', hour12: false }; const localTime = new Date().toLocaleTimeString([], options); console.log(localTime); // "14:35", Welcome to the 24-hour world!

Time manipulation magic

For dynamic adjustments in user interfaces, simply transfer the time to a variable and update as required:

let currentTime = new Date().toLocaleTimeString(); // Every second, we have a rendezvous with destiny setInterval(() => { currentTime = new Date().toLocaleTimeString(); }, 1000);

Milliseconds mania

Get the current time in milliseconds since the Unix Epoch time zero using getTime():

const milliseconds = new Date().getTime(); console.log(milliseconds); // 1679875723511, Time flies, even in milliseconds!

Time trimming

For a sleek display, you can evict seconds:

const cleanTime = new Date().toLocaleTimeString().replace(/:\d+ /, ' '); console.log(cleanTime); // "2:35 PM", now that's clean living!

Bridging the HTML5 gap

To directly insert the current time in an HTML5 <input type="time">:

<input type="time" id="timePicker"> <script> const inputElement = document.getElementById('timePicker'); inputElement.value = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false}); // Now that's what I call a time machine! </script>

Real-world implementation

User interfaces

When showcasing the current time in an interactive environment, keep the local time and audience preferences in mind.

Time-based events

Ingrain the time retrieval into click events for those instant time-related interactions.

Real-time updates

In applications requiring live explorations of time such as clocks or countdowns, employ setInterval to keep the ticking and tocking backpacked with the clock.