简体   繁体   中英

Populate the upcoming Thursday with JavaScript

I'm trying to populate the upcoming Thursday with JavaScript. This works until the end of the month. If it's the 25th of August - the script with populate "Next Thursday - 8/32/2022".

I'm looking for a smarter solution to support months etc.

 document.getElementById("mydiv").innerHTML = getNextThursday(); function getNextThursday() { var today = new Date(); var year = today.getFullYear(); var mes = today.getMonth()+1; var dia = today.getDate() + ((7 - today.getDay() + 4) % 7 || 7); var fecha = "Next Thursday - "+mes+"/"+dia+"/"+year; return fecha; }
 <span id="mydiv"> Date</span>

Set the date to next Thursday first, then get the year, month and day values, eg

 function getNextThursday(date = new Date()) { // Copy date so don't affect original let d = new Date(date); // Set d to next Thursday first d.setDate(d.getDate() + ((7 - d.getDay() + 4) % 7 || 7)); return d; } [new Date(2022,7,24), // Wed 24 Aug 2022 new Date(2022,7,25), // Thu 25 Aug 2022 new Date(2022,7,26), // Fri 26 Aug 2022 new Date() // Today ].forEach(d => console.log( d.toDateString() + ' -> ' + getNextThursday(d).toDateString()) );

If I keep your logic, you must only use the native setDate() to setup a date.

function getNextThursday() {
  const d = new Date();
  d.setDate(d.getDate() + (((4 + 7 - d.getDay()) % 7) || 7));

  const year = d.getFullYear();
  const mes = d.getMonth()+1;
  const dia = d.getDate();
 
 const fecha = "Next Thursday - "+mes+"/"+dia+"/"+year;

  return fecha;
} 

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