Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of weeks between two dates using JavaScript

Tags:

javascript

I'm trying to return the number of weeks between two dates using JavaScript.

So I have the following variables:

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if(day < 10) { day= '0' + day; }
if(month < 10) { month = '0' + month; }

var dateToday = day + '/' + month + '/' + year;

var dateEndPlacement = '22/06/2014';

I've also prefixed the days and months with 0 if they are less than 10. Not sure if this is the correct way to do this... so alternative ideas would be welcomed.

And then I pass these two dates to the following function:

function calculateWeeksBetween(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);
}

However I get the error:

Uncaught TypeError: Object 04/04/2014 has no method 'getTime'

Any ideas what I am doing wrong?

For those that are asking/gonna ask, I'm calling the function like this:

 calculateWeeksBetween(dateToday, dateEndPlacement);
like image 874
Cameron Avatar asked Apr 04 '14 10:04

Cameron


People also ask

How do I calculate the number of weeks between two dates in Excel?

To find out how many weeks there are between two dates, you can use the DATEDIF function with "D" unit to return the difference in days, and then divide the result by 7.

How do I find the number of weeks between two dates in Python?

We will take the absolute value of this by using the abs() function to prevent the negative value. After this, we have to simply divide this value by 7 to get the difference between these two dates in number of weeks. Here we will use '//' (floor division) operator to ignore the float value after division.


1 Answers

I would recommend using moment.js for this kind of thing.

But if you want to do it in pure javascript here is how I would do it:

function weeksBetween(d1, d2) {
    return Math.round((d2 - d1) / (7 * 24 * 60 * 60 * 1000));
}

Then call with

weeksBetween(new Date(), new Date(2014, 6, 22));
like image 143
Jack Allan Avatar answered Nov 02 '22 23:11

Jack Allan