Skip to content

Commit 0a9999e

Browse files
Pedro MedeirosPedro Medeiros
authored andcommitted
add days between dates in date_and_times chapter
1 parent 2619e15 commit 0a9999e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
layout: recipe
3+
title: Get Days Between two Dates
4+
chapter: Dates and Times
5+
---
6+
7+
h2. Problem
8+
9+
You need to find how much seconds minutes, hours, days, months or years has passed between two dates.
10+
11+
h2. Solution
12+
13+
Use JavaScript's Date function getTime(). Which provides how much time in miliseconds has passed since 01/01/1970:
14+
15+
{% highlight coffeescript %}
16+
DAY = 1000 * 60 * 60 * 24
17+
18+
d1 = new Date('02/01/2011')
19+
d2 = new Date('02/06/2011')
20+
21+
days_passed = Math.round((d2.getTime() - d1.getTime()) / DAY)
22+
{% endhighlight %}
23+
24+
h2. Discussion
25+
26+
Using miliseconds makes the life easier to avoid overflow mistakes with Dates. So we first calculate how much miliseconds has a day.
27+
Then, given two distincit dates, just get the diference in miliseconds betwen two dates and then divide by how much miliseconds has a
28+
day. It will get you the days between two distinct dates.
29+
30+
If you'd like to calculate the hours between two dates objects you can do that just by dividing the diference in miliseconds by the
31+
convertion of miliseconds to hours. The same goes to minutes and seconds.
32+
33+
{% highlight coffeescript %}
34+
HOUR = 1000 * 60 * 60
35+
36+
d1 = new Date('02/01/2011 02:20')
37+
d2 = new Date('02/06/2011 05:20')
38+
39+
hour_passed = Math.round((d2.getTime() - d1.getTime()) / HOUR)
40+
{% endhighlight %}
41+

0 commit comments

Comments
 (0)