最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Calculate date difference in weeks (Javascript) - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Dec 14, 2013 at 20:04 user2368182user2368182 9
  • "doesn't seem to work." What does that mean? Error? NaN? – bjb568 Commented Dec 14, 2013 at 20:07
  • 1 I'll answer my question. I got NaN because '2012-15-12' is an "Invalid Date" – bjb568 Commented Dec 14, 2013 at 20:08
  • Changed my post. It returns everything, but not the expected result. – user2368182 Commented Dec 14, 2013 at 20:08
  • Tips: There is to need to used ` getTime` to convert it to millisecond. – Derek 朕會功夫 Commented Dec 14, 2013 at 20:08
  • Seems like your time string is not rfc2822 pliant – bjb568 Commented Dec 14, 2013 at 20:10
 |  Show 4 more ments

2 Answers 2

Reset to default 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.

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!

发布评论

评论列表(0)

  1. 暂无评论