Languages
[Edit]
EN

JavaScript - calculate time period (time difference in days, minutes, seconds and milliseconds)

5 points
Created by:
Gigadude
791

In this article, we're going to have a look at how to calculate the time period between two dates in JavaScript.

The first thing that we should mention is the fact the number of days in different months and years is different so the easiest way is to express it as a number of days, hours, minutes, seconds, and milliseconds.

 

Custom time period example

Edit

In this section, dates are converted to milliseconds difference. Based on the difference we are able in a simple way to calculate the amount of days, hours, minutes, etc.

 

Alternative implementation example

Edit

This approach allows to:

  • render string with the indicated amount of parts (e.g. 2 parts 10s 30min),
  • use custom units (labels array as the last argument),
  • select a message to display when the precision of labels is not enough (e.g. done variable can be set as 'Now' when we want to say the comment was posted now - not 100ms ago).

Note:

  • this approach is not perfect because of different days per one year, but for displaying aproximate period time it is enought (e.g. comments system),
  • to solve the problem we can remove years part from code.

 

Alternative titles

  1. JavaScript - calculate time span (timespan)
  2. JavaScript - calculate time moment
  3. JavaScript - how to calculate time period (time difference in days, minutes, seconds and milliseconds)?
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join