0

The following script gives me next friday and next sunday date. It works fine but for some reasons at Saturday night for some hours it returns me next thursday and next saturday instead of the correct date.

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);

console.log('Next Friday     : ' +  nextFriday.toDateString() +
  '\nFollowing Sunday: ' + followingSunday.toDateString()); 

/* Previous code calculates next friday and next sunday dates */

$(document).ready(function() {
  var checkinf = nextWeekdayDate(null, 5);
  var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
  var checkouts = nextWeekdayDate(null, 7);
  var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
};

Anybody can explain why and how to fix this ? thanks

RobG
  • 124,520
  • 28
  • 153
  • 188
Francesco
  • 61
  • 5
  • Because *toISOString* returns UTC values, so for the period of the local timezone offset near midnight it will return the wrong date, either the day before for eastern offsets or the day after for western offsets. See [*How to format a JavaScript date*](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date?r=SearchResults&s=1|1450.4192). – RobG Jun 07 '20 at 10:28
  • That post has lot of informations, i can't get the point where explains my problem. Is there something i should use instead of toISOString ? – Francesco Jun 07 '20 at 17:12

0 Answers0