How to create a dynamic link with a specific date

Viewed 282

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> 
1 Answers

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}`);
    });
});
Related