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));
Author by
Admin
Updated on June 11, 2022Comments
-
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 over 10 yearsReturns 2239 instead of 52 :)
-
bjb568 over 10 years@user2368182 I got "Fri Jan 16 1970 17:17:30 GMT-0800 (PST)" from
new Date(1387050870);
-
charlietfl over 10 yearsif first value is a unix timestamp need to multiply by 1000 first
-
Josiah Hester over 10 yearsAh, you didnt specify the timestamp type, so I assumed milliseconds
-
bjb568 over 10 years@charlietfl Exactly. I think it should probably be
new Date(1387050870000);
which gives 2014 -
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 over 10 years@charlietfl That's it :) Now, i get -52, which is correct. Ty.
-
Admin over 10 yearsJust a little thing: The timestamp doesn't need to be a Date object.
-
olefrank over 9 yearsUse Math.floor instead of Math.round
-
Noor about 8 yearsIt 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