-3

I want to add all Saturdays of 2020/2021 into an object like following:

saturdays = {
   "Saturday, 22.02.2020" : "Saturday, 22.02.2020" ,
   "Saturday, 29.02.2020" : "Saturday, 29.02.2020"
}
Siva K V
  • 10,561
  • 2
  • 16
  • 29
Umut885
  • 165
  • 1
  • 15

2 Answers2

0

It is an unusual format (name is the same as the value) and objects are not ordered so don't expect to get them back in any particular order . . . but it is pretty trivial to do if you want . . .

    saturdays = {};

    function loadSaturdays(startYear, endYear) {
        const SATURDAY = 6;
        let start = new Date("01/01/" + startYear);
        let end = new Date("12/31/" + endYear);
        var dateOptions = {weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric'};

        var current = new Date(start);
        while (current <= end) {
            if (SATURDAY === current.getDay()) {
                let newSaturday = "\"" + current.toLocaleString('en-GB', dateOptions).replace(/\//gi, '.') + "\"";
                // if you want to see the individual ones as you are building the object
                // console.log(newSaturday);
                saturdays[newSaturday] = newSaturday;
            }
            current = new Date(current.setDate(current.getDate() + 1));
        }
    }

    loadSaturdays("2020", "2021");

    // if you want to see the entire object
    //console.log(saturdays);

    // objects are not ordered but they are all there
    for (saturday in saturdays) {
        console.log(saturday);
    }
0

1) First find out number of days in year (daysInYear method)
2) Find out first saturday date (firstSatDate method)
3) Go over for loop from first saturday to end of the year day and build the date string requirement format.

const daysInYear = year =>
  (new Date(year + 1, 0, 1) - new Date(year, 0, 1)) / (24 * 60 * 60 * 1000);

const firstSatDate = year => {
  const week_day = new Date(year, 0, 1).getDay();
  const satDate = new Date(year, 0, 7 - week_day);
  return satDate.getDate();
};

const getSaturdays = year => {
  const yearDays = daysInYear(year);
  const first = firstSatDate(year);
  const saturdays = {};
  for (let day = first; day <= yearDays; day = day + 7) {
    const date = new Date(year, 0, day);
    const day_str = String(date.getDate()).padStart(2, '0');
    const month_str = String(date.getMonth() + 1).padStart(2, '0');
    const date_str = `Saturday, ${day_str}.${month_str}.${date.getFullYear()}`;
    saturdays[date_str] = date_str;
  }
  return saturdays;
};

console.log(getSaturdays(2020));
console.log(getSaturdays(2021));
Siva K V
  • 10,561
  • 2
  • 16
  • 29