Calculate date difference in weeks (Javascript)

2019-06-22 02:06发布

问题:

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.

回答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.



回答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!