简体   繁体   中英

Calculate a pair of dates connected together

The following code outputs me next Friday and next Sunday . I need to output next Friday and next Sunday after the outputted Friday ,not just next Sunday. Otherwise If today is Friday or Saturday, It won't work.
Example: if today is Friday 05/06 my output will be Friday 05/13 and Sunday 05/07 instead of Sunday 05/15 (that is the output I need).

That is the code I'm using actually. How can I fix it to make it work?

<script type="text/javascript">
 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));

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


             window.open( "https://www.mydynamiclink.com" + variables );

                            });

        });


</script>

thanks:)

I think for the checkouts , you can simply increase the checkinf by two days if your checkinf are correctly outputted.

What I mean is this: Instead of var checkouts = nextWeekdayDate(null, 7);

Your should do this:

var checkouts = checkinf.setDate(checkinf.getDay() + 2); //For the next sunday

The assignment:

var checkouts = nextWeekdayDate(null, 7);

gets the next Sunday after today. What you want is the Sunday after checkinf , so pass it in the call. Also, the day number for Sunday is 0:

var checkouts = nextWeekdayDate(checkinf, 0);

 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM