Reputation: 626
I need to find the number of weeks passed from a particular month, till date.
Like if its Nov, 2013 (as of today, 10th Jan, 2014) it should return 9 weeks.
Is there a way to find it?
Upvotes: 0
Views: 1711
Reputation: 1003
That's a little vague, and the other answers are correct - it's basically just maths once you understand how to get milliseconds out of a date...
Try this fiddle as a start;
http://jsfiddle.net/melchizidech/UGWe6/
Date.prototype.daysSince = function(newDate){
var difference = this.valueOf() - newDate.valueOf();
var msInDay = 1000 * 60 * 60 * 24;
var days = Math.floor(difference / msInDay);
return days;
};
Upvotes: 1
Reputation: 17735
Try this:
function weeksSince(dateString){
var date = new Date(dateString);
var today = new Date();
return Math.floor((today-date)/(1000*60*60*24*7));
}
console.log(weeksSince("January 01, 2014"));
console.log(weeksSince("January 01, 2013"));
console.log(weeksSince("January 01, 2012"));
=> 1
=> 53
=> 105
Upvotes: 2
Reputation: 82231
Try This:
function weeks_between(date1, date2) {
// The number of milliseconds in one week
var ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to weeks and return hole weeks
return Math.floor(difference_ms / ONE_WEEK);
}
If you want them to be very precise(including days and time) then use these jquery libraries for that:
Upvotes: 1
Reputation: 70122
Try the following:
function differenceInWeeks(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
}
The getTime
function returns the number of milliseconds since 1970/01/01, the rest is just maths.
Upvotes: 3