开发者

How to calculate the number of weeks in a month

I want开发者_运维知识库 to calculate the total no of weeks in current month. Starting from Sunday or Monday.

Is it possible to do in Qt


I would say this problem is not specific to Qt, but Qt can help you with the QDate class. With this class you can get the current month :

QDate CurrentDate = QDate::currentDate();

The number of days of a given month :

CurrentDate.daysInMonth();

For the number of week calculation, it depends if you only want the number of full weeks in a month, or the number of weeks, taking partial weeks into account.

For the latter, here is how I would do it (considering the week starts on monday) :

const DAYS_IN_WEEK = 7;
QDate CurrentDate = QDate::currentDate();
int DaysInMonth = CurrentDate.daysInMonth();
QDate FirstDayOfMonth = CurrentDate;
FirstDayOfMonth.setDate(CurrentDate.year(), CurrentDate.month(), 1);

int WeekCount = DaysInMonth / DAYS_IN_WEEK;
int DaysLeft = DaysInMonth % DAYS_IN_WEEK;
if (DaysLeft > 0) {
   WeekCount++;
   // Check if the remaining days are split on two weeks
   if (FirstDayOfMonth.dayOfWeek() + DaysLeft - 1 > DAYS_IN_WEEK)
      WeekCount++;
}

This code has not been fully tested and is not garanteed to work !


floor(Number of Days / 7)


QDate::weekNumber can give you the number of the week in the year.

Here is an example of how to use it to obtain the number of weeks in a month, including those shorter than seven days:

QDate dateCurrent = QDate::currentDate();
int year = dateCurrent.year(), month = dateCurrent.month(),
daysInMonth = dateCurrent.daysInMonth(), weeksInMonth;

weeksInMonth = QDate(year, month, daysInMonth).weekNumber()
    - QDate(year, month, 1).weekNumber() + 1;


Some months have 4 weeks and others have 5. Qt states that:

In accordance with ISO 8601, weeks start on Monday and the first Thursday of a year is always in week 1 of that year. Most years have 52 weeks, but some have 53.

For that matter my first Thursday in a month is the starting point when counting the number of weeks in a month. The function below works for me:

int myClass::weeksInMonth(QDate cdate)
{
    QDate sDte = QDate(cdate.year(),cdate.month(),1);
    QDate eDte = QDate(cdate.year(),cdate.month(),cdate.daysInMonth());
    int wks = 0;
     for(QDate stD = sDte; stD <= eDte; stD = stD.addDays(1)){
       if(stD.dayOfWeek() == Qt::Thursday)++wks;
     }
     return wks;
}


Here's a function that wraps the top answer for PyQt5. However the ISO 8601 definition for week 01 is the week with the first Thursday of the Gregorian year; this solution will give a negative number of weeks on dec and jan on certain years..

def weeksInMonth(date: QDate):
    year = date.year(), month = date.month()
    daysInMonth = date.daysInMonth()
    return QDate(year, month, daysInMonth).weekNumber()[0] - QDate(year, month, 1).weekNumber()[0] + 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜