Home > Net >  Populate the upcoming Thursday with JavaScript
Populate the upcoming Thursday with JavaScript

Time:08-26

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>

CodePudding user response:

Set the date to next Thursday first, then get the year, month and day values, e.g.

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

CodePudding user response:

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;
} 
  • Related