-1

I need to find the difference in hours between a certain date and Sunday at 00:01 on the same week.

For example, if the given date is today (Saturday, June 18 2016), I need to find the difference between it and Sunday, June 12 2016 at 00:01.

I basically need to go back from the given date to its last Sunday and find the difference.

This is what I have

var date = new Date($scope.newGame.date);
var time = $scope.newGame.time.replace(':', ',');
date.setHours(parseInt(time));
date = date.getTime();
console.log(date); // Logs 1466272800000

var t = new Date().getDate() + (8 - new Date().getDay() - 1) - 7 ;
var d = new Date();
d.setHours(0,0,0,1);
d.setDate(t);
var lastSunday = new Date(d).getTime();

var hourDiff = 1466272800000 - lastSunday;
var hoursDifference = Math.floor(hourDiff/1000/60/60);
console.log(hoursDifference); // Logs 164

This works well. Now I just need to find the difference if the given date is not on this week by going back to its last Sunday

  • 1
    So what have you tried? it is not hard to do web search for javascript date difference. This is not a coding service and you are expected to show attempts you have made to solve problem yourself. Then we help with code that doesn't work as epected – charlietfl Jun 18 '16 at 17:19
  • OK...much better. Idea here is to help fix real code...not start from scratch – charlietfl Jun 18 '16 at 18:17

1 Answers1

1

I would break this into two issues:

  1. How to get the difference between two Date objects, and
  2. How to get a Date object for the Sunday before a given Date (at Midnight at the start of the day).

To get the difference:

function getDateDiff(date1, date2) {
    return date2.getTime() - date1.getTime();
}

reference


To get Sunday:

function getSunday(date) {
    var newDate = new Date(date);
    newDate.setDate(date.getDate() - date.getDay());
    newDate.setHours(0, 0, 0, 0);
    return newDate;
}

reference


Your code can then look like this:

var date = new Date(2016, 5, 18, 13, 30, 0, 0); // 2016/06/18 at 1:30PM

console.log(date);
console.log(getSunday(date));

var diff = getDateDiff(getSunday(date), date);

console.log(diff);

var hourDiff = Math.floor(diff/1000/60/60);

console.log(hourDiff);

jsfiddle

Community
  • 1
  • 1
John S
  • 21,212
  • 8
  • 46
  • 56