2

I need to generate a dynamic link using the date of "next Friday" as a variable for my link.

I found this code that should always output the next Friday 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;
}

var date = new Date();
console.log(nextWeekdayDate(date, 5));

but I can't figure out how to make it work with the next code connected with a button into my HTML page. How can I pick the next Friday date as a variable?

$(document).ready(function(){

    $('#button').click(function(e) {  
      var date = ;

        window.open( "https://www.mydinamiclink.com/"+date );

    });
});
</script> 
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Francesco
  • 95
  • 6

1 Answers1

0

You can use nextWeekdayDate with the index 5 for Friday:

$(document).ready(function() {
    $('#button').click(function(e) {  
        var date = nextWeekdayDate(null, 5);
        var [yyyy, mm, dd] = date.toISOString().split('T')[0].split('-');
        if (mm.startsWith('0')) mm = mm.slice(1);
        window.open(`https://www.mydinamiclink.com/${yyyy}${mm}${dd}`);
    });
});
willystyle
  • 209
  • 1
  • 5
  • *toISODate* returns UTC values so will return the wrong date within the local offset of midnight. For formatting date strings, 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 May 25 '20 at 20:29
  • Thank you. Is there a way to output the month removing the 0 digit ? For example May should be 5, while October should still be 10 – Francesco May 26 '20 at 12:03
  • sure, see line removing leading zero in month – willystyle May 27 '20 at 14:58