w3resource

JavaScript: Get time differences in weeks between two dates

JavaScript Datetime: Exercise-47 with Solution

Write a JavaScript function to get time differences in weeks between two dates.

Test Data :
dt1 = new Date("June 13, 2014 08:11:00");
dt2 = new Date("October 19, 2014 11:13:00");
console.log(diff_weeks(dt1, dt2));
18

Sample Solution:

JavaScript Code:

// Define a function diff_weeks that calculates the difference in weeks between two given Date objects, dt2 and dt1
function diff_weeks(dt2, dt1) 
{
  // Calculate the difference in milliseconds between dt2 and dt1
  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  // Convert the difference from milliseconds to weeks by dividing it by the number of milliseconds in a week
  diff /= (60 * 60 * 24 * 7);
  // Return the absolute value of the rounded difference as the result
  return Math.abs(Math.round(diff));
}

// Create Date objects representing two dates
dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,11);
// Calculate and output the difference in weeks between the two dates
console.log(diff_weeks(dt1, dt2));

// Create Date objects representing two other dates
dt1 = new Date("June 13, 2014 08:11:00");
dt2 = new Date("October 19, 2014 11:13:00");
// Calculate and output the difference in weeks between these two dates
console.log(diff_weeks(dt1, dt2));

Output:

1
18

Explanation:

In the exercise above,

  • This JavaScript code defines a function "diff_weeks()" that calculates the difference in weeks between two given dates ('dt2' and 'dt1').
  • The function takes two Date objects as input parameters.
  • It calculates the difference in milliseconds between the two dates using their "getTime()" method.
  • Then, it converts the difference from milliseconds to weeks by dividing it successively by the number of milliseconds in an hour, a day, and a week.
  • The result is rounded to the nearest integer using "Math.round()".
  • Finally, the absolute value of the rounded difference is returned as output.

Flowchart:

Flowchart: JavaScript- Get time differences in weeks between two dates

Live Demo:

See the Pen JavaScript - Get time differences in weeks between two dates-date-ex-47 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to get time differences in days between two dates.
Next: Write a JavaScript function to get time differences in months between two dates.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-date-exercise-47.php