clock  Mon - Sun 8.00 AM - 8.00 PM
fb
instagram
play store
pinterest

How to Get Remaining Time Between Two Dates in Vue JS using Javascript Function

writter  Sumit Dey Sarkar
Date  27 Dec 2022
Language  Vue JS
How to Get Remaining Time Between Two Dates in Vue JS using Javascript Function

How to Get Remaining Time Between Two Dates in Vue JS using Javascript Function

In this tutorial we will learn how to calculate time difference between two dates in vue js using javascript function.

We can use this function to get the remaining time in days, remaining time in hours and remaining time in minutes and seconds. This function will also return the remaining time in percentage. You can use the percentage value in your countdown progress bar.

Step 1 - Create a view component.

Step 2- In the second step, simply paste the following code in your view component.

<template lang="">
  <div>
    <h1>Get Remaining Time Between Two Dates</h1>
    <p>Days : {{time.days}}</p>
    <p>Hours : {{time.hours}}</p>
    <p>Minutes : {{time.minutes}}</p>
    <p>Seconds : {{time.seconds}}</p>
    <p>Time left in (%) : {{time.percentage}}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      time:[]
    }
  },
  methods: {
    getRemainingTime: function(start, end) {
      let remainingTime = {
        days: "0",
        hours: "0",
        minutes: "0",
        seconds: "0",
        percentage: 0.1,
        timeleft:false
      };
 
      if (new Date() < new Date(end)) {
        let a = new Date(end).getTime();
        let b = new Date().getTime();
        let c = new Date(start).getTime();
        let difference = a - b;
        if (difference > 0) {
          remainingTime = {
            days: Math.floor(difference / (1000 * 60 * 60 * 24)).toString(),
            hours: Math.floor((difference / (1000 * 60 * 60)) % 24).toString(),
            minutes: Math.floor((difference / 1000 / 60) % 60).toString(),
            seconds: Math.floor((difference / 1000) % 60).toString(),
            percentage: 100 - Math.floor((b - c) / (a - c) * 100),
            timeleft:true
          };
        }
      }
      console.log(remainingTime);
      return remainingTime;
    },
  },
  mounted() {
    this.time = this.getRemainingTime('2022-12-19', '2023-01-02');
  },
};
</script>
<style lang="">
</style>

 

Step 3 - Now, start the npm server

 

Output

How to Get Remaining Time Between Two Dates in Vue JS