8

I have two strings:

1387050870

and

2012-12-15

How can i calculate the difference between these two dates in weeks (52)?

I tried Math.round(1387050870-(Math.round(new Date('2012-12-15').getTime()/1000))/604800), but that doesn't seem to work.

2 Answers2

7

The JavaScript Date object accepts milliseconds as its constructor, so convert first then try:

var a  = new Date(1387050870 * 1000);
var b = new Date("2012-12-15");
var weeks = Math.round((a-b)/ 604800000);

Which makes weeks 2239, which sounds close, since b is almost 43 years later * 52 weeks.

Josiah Hester
  • 6,065
  • 1
  • 24
  • 37
  • Returns 2239 instead of 52 :) –  Dec 14 '13 at 20:16
  • @user2368182 I got "Fri Jan 16 1970 17:17:30 GMT-0800 (PST)" from `new Date(1387050870);` – bjb568 Dec 14 '13 at 20:16
  • 2
    if first value is a unix timestamp need to multiply by 1000 first – charlietfl Dec 14 '13 at 20:17
  • 1
    Ah, you didnt specify the timestamp type, so I assumed milliseconds – Josiah Hester Dec 14 '13 at 20:17
  • @charlietfl Exactly. I think it should probably be `new Date(1387050870000);` which gives 2014 – bjb568 Dec 14 '13 at 20:18
  • `var a = new Date(1387050870000); var b = new Date("2012-12-15"); var weeks = Math.round((b-a)/ 604800000);` returns -52 – charlietfl Dec 14 '13 at 20:18
  • @charlietfl That's it :) Now, i get -52, which is correct. Ty. –  Dec 14 '13 at 20:18
  • Just a little thing: The timestamp doesn't need to be a Date object. –  Dec 14 '13 at 20:19
  • Use Math.floor instead of Math.round – olefrank Jan 11 '15 at 21:47
  • It depends on what do we means by different of weeks between two dates, do we mean the difference of week as a time interval difference or a calender interval as a difference, using the chosen solution for this questions, we get a 0 week difference for 4/01/2015 and 5/01/2015 but there is one week calender difference between the two – Noor Apr 23 '16 at 19:26
4

Try this:

var date1 = new Date(1387050870 * 1000);
var date2 = new Date("2012-12-15");
var dif = Math.round(date1-date2);
alert(Math.round(dif/1000/60/60/24/7));

Here it is on jsfiddle!

Peter Warrington
  • 654
  • 10
  • 32
Nouphal.M
  • 6,304
  • 1
  • 17
  • 28