Calculate date difference in weeks (Javascript)

10,169

Solution 1

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.

Solution 2

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!

Share:
10,169
Admin
Author by

Admin

Updated on June 11, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

  • Admin
    Admin over 10 years
    Returns 2239 instead of 52 :)
  • bjb568
    bjb568 over 10 years
    @user2368182 I got "Fri Jan 16 1970 17:17:30 GMT-0800 (PST)" from new Date(1387050870);
  • charlietfl
    charlietfl over 10 years
    if first value is a unix timestamp need to multiply by 1000 first
  • Josiah Hester
    Josiah Hester over 10 years
    Ah, you didnt specify the timestamp type, so I assumed milliseconds
  • bjb568
    bjb568 over 10 years
    @charlietfl Exactly. I think it should probably be new Date(1387050870000); which gives 2014
  • charlietfl
    charlietfl over 10 years
    var a = new Date(1387050870000); var b = new Date("2012-12-15"); var weeks = Math.round((b-a)/ 604800000); returns -52
  • Admin
    Admin over 10 years
    @charlietfl That's it :) Now, i get -52, which is correct. Ty.
  • Admin
    Admin over 10 years
    Just a little thing: The timestamp doesn't need to be a Date object.
  • olefrank
    olefrank over 9 years
    Use Math.floor instead of Math.round
  • Noor
    Noor about 8 years
    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