Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript calculates the number of days between two dates


May 09, 2021 CoffeeScript


Table of contents


Calculate the number of days between the two dates

Problem

You need to find out the two dates are separated by years, months, days, hours, minutes, seconds.

Solution

Use JavaScript's date calculation function getTime(). It provides how many milliseconds have passed since January 1, 1970.

DAY = 1000 * 60 * 60  * 24

d1 = new Date('02/01/2011')
d2 = new Date('02/06/2011')

days_passed = Math.round((d2.getTime() - d1.getTime()) / DAY)

Discuss

Use milliseconds to make it easier to calculate time spans to avoid date overflow errors. S o we first calculate how many milliseconds there are in a day. T hen, 2 different dates are given, only the number of milliseconds between 2 dates is known, and then divided by the number of milliseconds of the day, which will get the number of days between 2 different dates.

If you want to calculate the number of hours for 2 date objects, you can divide the millisecond interval by one hour and how many milliseconds. The same can get a few minutes and a few seconds.

HOUR = 1000 * 60 * 60

d1 = new Date('02/01/2011 02:20')
d2 = new Date('02/06/2011 05:20')

hour_passed = Math.round((d2.getTime() - d1.getTime()) / HOUR)