Vue Js Calculate Days Between Dates: To calculate the number of days between the current date and a previous date in Vue.js, you can use the JavaScript Date
object to create instances of the current date and the previous date, then calculate the difference between them in days.In this tutorial we will learn how to calculate days between dates using native javascript and Vue js
How to calculate Days Between Dates in Vue Js
We’re using a computed property called daysSinceLastDate
to calculate the number of days between the current date and the date stored in the lastDate
data property. To do this, we:
- Create instances of the current date and the previous date using the
new Date()
constructor. - Get the time in milliseconds since the Unix epoch for each date using the
getTime()
method. - Calculate the difference between the two dates in milliseconds.
- Divide the difference by the number of milliseconds in a day to get the number of days difference.
- Return the number of days difference as the computed property value.
Vue Js Calculate Days between Dates Example
<div id="app">
<p>Last date: {{ lastDate }}</p>
<p>Days since last date: {{ daysSinceLastDate }}</p>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
lastDate: '2023-02-15', // Replace with your own date
};
},
computed: {
daysSinceLastDate() {
const currentDate = new Date()
const previousDate = new Date(this.lastDate)
const timeDifference = currentDate.getTime() - previousDate.getTime()
const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24))
return daysDifference
},
},
});
app.mount('#app');
</script>