In Vue.js, you can get the current time in 24-hour format by creating a new Date object and formatting it using the toLocaleTimeString
method with appropriate options. The toLocaleTimeString
method returns a string representation of the time in the current locale format.In this Example we will learn how to get current time in 24 hours format using Vue js and Native javascript.
How to get Current Time in 24 hours format?
In this code, the mounted()
lifecycle hook calls the getCurrentTime()
method, which gets the current time using the Date
object and formats it with the toLocaleTimeString()
method. The setInterval()
function is used to update the time every second.
The options
object is passed to toLocaleTimeString()
to format the output in 24-hour format. The hour12
option is set to false
to indicate 24-hour format, and the hour
, minute
, and second
options are set to '2-digit'
to display leading zeros for single-digit numbers.
The currentTime
variable is used in the template to display the current time.
Vue js Get Current Time in 24 hours foramt Example
<div id="app">
<p>Current Time: {{ currentTime }}</p>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
currentTime: null
}
},
mounted() {
this.getCurrentTime();
},
methods: {
getCurrentTime() {
const options = {
hour12: false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
const now = new Date();
this.currentTime = now.toLocaleTimeString('en-US', options);
setInterval(() => {
this.currentTime = new Date().toLocaleTimeString('en-US', options);
}, 1000);
}
}
});
app.mount('#app');
</script>