Date and time are some of the most important aspects of any web application (mostly current date and time). It’s in fact, almost impossible to create a full application without having to use date and time. In this short tutorial, I’ll show you how to get the current date and time in real-time using Vue.js.
This is the code you’d need to show date and time with a latency of 1 second (1000 ms):
<template>
<div id="app">
<div class="np-title">Realtime Date Time</div>
<div class="np-time">
{{ currentDateTime }}
</div>
<div class="np-credits">www.nightprogrammer.com</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
currentDateTime: null,
};
},
mounted() {
setInterval(() => {
this.currentDateTime = new Date();
}, 1000);
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 12px;
}
.np-title {
font-size: 20px;
}
.np-time {
font-size: 24px;
font-weight: 600;
margin: 12px 0px;
border: 1px solid #eee;
background: #003cff;
padding: 4px 10px;
color: #fff;
max-width: 490px;
border-radius: 6px;
}
.np-credits {
font-size: 12px;
}
</style>
Code language: HTML, XML (xml)
As you can see, all I’ve done is created a setInterval method by initialising the current date and time to the currentDateTime local state. On line 22, I’ve passed 1000 (ms) as the interval in which setInterval will repeat the instructions written inside it. That means, the currentDateTime local state is getting initialised again and again with a new Date() method. And whenever there’s an update to the value of a state, Vue will re-render the component causing it. Thus, you’ll see live time.
Here’s a preview of the view:
And here’s a working demo of the above code: