Мне нужно круглое количество недель в месяц согласно стандарту ISO.
Кроме того, я использую momentJS вместо даты Js.
в соответствии с форматом даты ИСО неделя считается для этого месяца, если у нее четверг, в противном случае она считается для предыдущего месяца.
в соответствии с тем, что число округленных недель в этом году равно 5 ( 2018 ):
Марс, май, август и ноябрь
говорят, что у остальных 4 недели.
Вот мой код (вдохновение здесь ):
РЕДАКТИРОВАТЬ, если я не применяю предложенное исправление в комментариях, у меня останется 1 неделя для декабря месяца на 2018 год, то же самое для 2017 года.
ngOnInit() {
this.generateTimelineForGivenYear('2018');
}
generateTimelineForGivenYear(year){
for (let i = 1; i < 13; i++) {
let month;
if (i < 10) month = '0'.concat(i.toString());
else month = i;
this.howManyWeeksForGivenMonth(moment(year + '-'+ month + '-05'));
}
}
howManyWeeksForGivenMonth(myDate){
console.log('The Month : ', myDate.month() + 1);
const start = myDate.clone().startOf('month').week();
let end = myDate.clone().endOf('month').week();
if( start > end ){ end = 52 + end }
const res = end - start;
console.log('The Number of Weeks: ', res);
console.log('----------------------------------------------------');
}
мой результат:
The Month : 1
The Number of Weeks: 4
----------------------------------------------------
The Month : 2
The Number of Weeks: 4
----------------------------------------------------
The Month : 3
The Number of Weeks: 4
----------------------------------------------------
The Month : 4
The Number of Weeks: 4
----------------------------------------------------
The Month : 5
The Number of Weeks: 4
----------------------------------------------------
The Month : 6
The Number of Weeks: 4
----------------------------------------------------
The Month : 7
The Number of Weeks: 4
----------------------------------------------------
The Month : 8
The Number of Weeks: 4
----------------------------------------------------
The Month : 9
The Number of Weeks: 5
----------------------------------------------------
The Month : 10
The Number of Weeks: 4
----------------------------------------------------
The Month : 11
The Number of Weeks: 4
----------------------------------------------------
The Month : 12
The Number of Weeks: 5
----------------------------------------------------
Как вы можете видеть, я получаю два месяца, которые равны 5 неделям, а также неправильных:
сентябрь и декабрь
Я тоже это попробовал:
howManyWeeksForGivenMonth(myDate){
console.log('The Month : ', myDate.month() + 1);
const first = myDate.day() == 0 ? 6 : myDate.day()-1;;
const day = 7-first;
const last = myDate.daysInMonth();
let res = Math.floor((last-day)/7);
if ((last-day) % 7 !== 0) res++;
console.log('The Number of Weeks: ', res);
console.log('----------------------------------------------------');
}
который дал:
The Month : 1
The Number of Weeks: 4
----------------------------------------------------
The Month : 2
The Number of Weeks: 3
----------------------------------------------------
The Month : 3
The Number of Weeks: 4
----------------------------------------------------
The Month : 4
The Number of Weeks: 4
----------------------------------------------------
The Month : 5
The Number of Weeks: 5
----------------------------------------------------
The Month : 6
The Number of Weeks: 4
----------------------------------------------------
The Month : 7
The Number of Weeks: 4
----------------------------------------------------
The Month : 8
The Number of Weeks: 5
----------------------------------------------------
The Month : 9
The Number of Weeks: 4
----------------------------------------------------
The Month : 10
The Number of Weeks: 4
----------------------------------------------------
The Month : 11
The Number of Weeks: 4
----------------------------------------------------
The Month : 12
The Number of Weeks: 4
----------------------------------------------------
... не лучше.
что я делаю не так?
ОБНОВЛЕНИЕ:
Как только выяснилось, что я не вырезаю в четверг, была проблема, вот моя новая попытка:
howManyWeeksForGivenMonth(myDate){
console.log('The Month ', myDate.month() + 1 );
let weeks = 4
if(myDate.clone().startOf('month').weekday() >= 5 ){
weeks ++;
console.log('first week extra');
}
if(myDate.clone().endOf('month').weekday() < 5 ) {
weeks ++;
console.log('last week extra');
}
return weeks;
}
Я получаю:
The Month 1
last week extra
5
The Month 2
last week extra
5
The Month 3
4
The Month 4
last week extra
5
The Month 5
last week extra
5
The Month 6
first week extra
5
The Month 7
last week extra
5
The Month 8
4
The Month 9
first week extra
last week extra
6
The Month 10
last week extra
5
The Month 11
4
The Month 12
first week extra
last week extra
6
здесь нечего читать, это просто мусор.
Очевидно, я понимаю, что оба ifs никогда не должны запускаться вместе в течение одного месяца, но я предполагал, что это просто не произойдет.
Я предположил, что неправильно, но, кроме того, это все еще не соответствует правильным месяцам. так что это сейчас?