Home > Back-end >  how to set the Date to the 1st Friday of the Current Year in javascript
how to set the Date to the 1st Friday of the Current Year in javascript

Time:10-18

I am trying to set the date to the 1st Friday of the Current Year in JavaScript.

var currentDate = new Date();
const firstMonth = "01"
var currentYear = currentDate.getFullYear();
var firstDay = new Date(currentYear, 0, 1);
var weekday = firstDay.getDay();
while (weekday != 5) {
  if (weekday < 5) {
    weekday = weekday   1;
  } else {
    weekday = weekday - 1;
  }
}

var friday = new Date(currentDate.setDate(firstDay.getDate()   6)).toUTCString();
console.log(friday)

CodePudding user response:

So first Friday of the current year can be in last year according to your code example? That would only work if you mean first Friday in the first week of the year

Here is first Friday of this year using your loop:

const currentDate = new Date();
const newYear = new Date(currentDate.getFullYear(), 0, 1, 15, 0, 0, 0); // make a date that is not near midnight anywhere
let day = newYear.getDay()
while (day != 5) {
  console.log(newYear.toString())
  newYear.setDate(newYear.getDate()   1);
  day = newYear.getDay();
}

console.log("Friday", newYear.toString())

CodePudding user response:

var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var firstDay = new Date(currentYear, 0, 1);
var weekday = firstDay.getDay();
while(weekday != 5)
{
        firstDay.setDate(firstDay.getDate() 1);
        weekday = firstDay.getDay();
 }
  • Related