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.
- "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
2 Answers
Reset to default 7The 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!