Вземете всички понеделници в годината

Винаги имам проблеми с намирането на функции за дати

var d = new Date(),
    month = d.getMonth(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === month) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}

Използвам тази функция, за да получа всички понеделници в месеца, текущия месец.

Как мога да адаптирам този код, за да получа всички останали понеделници в годината?


person Toni Michel Caubet    schedule 03.07.2017    source източник
comment
В края на последния цикъл: if (d.getMonth() === 0) break;   -  person Chris G    schedule 03.07.2017
comment
Ами while (d.getMonth() === month) { няма ли да трябва да го актуализирам?   -  person Toni Michel Caubet    schedule 03.07.2017
comment
Просто променете всичко, което се отнася до месеца, за да видите годината.   -  person Barmar    schedule 03.07.2017
comment
@ToniMichelCaubet Добре, можете основно да използвате while (true)   -  person Chris G    schedule 04.07.2017


Отговори (3)


Просто превъртете годината вместо месеца. Кодът е същият като вашия, работи добре. току-що променен месец -> година и getMonth() -> getYear()

var d = new Date(),
    year = d.getYear(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getYear() === year) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}
person Jose Gomez    schedule 03.07.2017

Това е само алтернатива, тя използва по-прост метод за получаване на първия ден от месеца.

// Get all Mondays in year from provided date
// Default today's date
function getMondays(d) {
  // Copy d if provided
  d = d ? new Date(+d) : new Date();
  // Set to start of month
  d.setDate(1);
  // Store end year and month
  var endYear = d.getFullYear() + 1;
  var endMonth = d.getMonth();

  // Set to first Monday
  d.setDate(d.getDate() + (8 - (d.getDay() || 7)) % 7);
  var mondays = [new Date(+d)];

  // Create Dates for all Mondays up to end year and month
  while (d.getFullYear() < endYear || d.getMonth() != endMonth) {
    mondays.push(new Date(d.setDate(d.getDate() + 7)));
  }
  return mondays;
}

// Get all Mondays and display result
// SO console doensn't show all results
var mondays = getMondays();
mondays.forEach(function(mon) {
  console.log(mon.toLocaleString(void 0, {
    weekday: 'short',
    day: 'numeric',
    month: 'short',
    year: 'numeric'
  }));
});

// Count of Mondays, not all shown in SO console
console.log('There are ' + mondays.length + ' Mondays, the first is ' + mondays[0].toString())

person RobG    schedule 04.07.2017

person    schedule
comment
Моля, не добавяйте дни чрез добавяне на 24 часа. На места, където се спазва лятното часово време, не всички дни са с продължителност 24 часа. Вижте Добавяне на +1 към текущата дата. - person RobG; 03.07.2017