Mouad Ennaciri
Mouad Ennaciri

Reputation: 1269

JavaScript - Calculate the difference between 2 dates (in year, days, hours or less than one hour)

I have 2 dates that I would like to have the difference of time between them.

if > one year show the number in year only, if > one day show the number of days, if < a day show the number of hours, if < an hour show "You have less than one hour left"

the simplest solution is to use Moment.js:

remainingTime() {
  moment.locale('fr_FR');
  return moment(new Date(this.finishedAt)).from(new Date(this.startedAt));
}

but does not give the exact result if the remaining time is less than a day.

how can we get the result preferably in native JavaScript or in Moment.js

Upvotes: 0

Views: 93

Answers (1)

Danyal Imran
Danyal Imran

Reputation: 2605

Its easy to achieve this in vanilla js. Remember that dates are represented in milliseconds therefore you can easily apply arithmetic operators on it.

const difference = (startDate, endDate) => endDate - startDate;

You can check for the difference in a function against seconds (60), minutes (3600), hours, (86400), months and years (depending on your condition to handle leap year and each month days calculation), and then return the appropriate value accordingly.

Upvotes: 1

Related Questions