简体   繁体   中英

How to get date of closest candidate days and next on each button click continuously

I am trying to get the date of closest Wednesday or/then Saturday based on given date on button click continuously. How can I achieve this?

 $(".btn-info").on("click", function(){ GetDate('2019-09-10'); }); function GetDate(x){ x = new Date(); var cc = x.setDate(x.getDate() + (1 + 5 - x.getDay()) % 7); console.log(cc); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <button type="button" class="btn btn-info">Get Next Wednesday / Saturday Date ++ </button>

  1. In your function getDate you are resetting the passed argument to todays date.
  2. You need to find out the current day and calculate how many days you need to add to get next wed / sat.
  3. You need to set the date by adding the calculated days.

Here is what should do:

 $(".btn-info").on("click", function(){ GetDate('2019-09-10'); // Next should be wed 9-11 GetDate('2019-09-12'); // Next should be sat 9-14 }); function GetDate(x){ x = new Date(x); // Current day can be from 0 (sunday) to 6 (Saturday); var currentDay = x.getDay(); var newDay = currentDay < 3 ? 3 : 6; var daysToAdd = newDay - currentDay; var cc = x.setDate(x.getDate() + daysToAdd); console.log(new Date(cc), new Date(cc).getDay()); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <button type="button" class="btn btn-info">Get Next Wednesday / Saturday Date ++ </button>

 $(".btn-info").on("click", function(){ var date = getNextWednesday('2019-09-10'); console.log(date) }); function getNextWednesday(date){ let x = new Date(date); x.setDate(x.getDate() + (3 + 7 - x.getDay()) % 7); return x; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" class="btn btn-info">Get Next Wednesday </button>

Something like this should work

 console.log(getNext("2019-09-09")); console.log(getNext("2019-09-10")); console.log(getNext("2019-09-11")); console.log(getNext("2019-09-12")); console.log(getNext("2019-03-06")); function getNext(dateStr) { const date = new Date(dateStr); const day = date.getDay(); const togo = day <= 3 ? 3 - day : 6 - day; date.setDate(date.getDate() + togo); return date; }

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