Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the number of weeks in a month

Tags:

qt

qt4

I want to calculate the total no of weeks in current month. Starting from Sunday or Monday.

Is it possible to do in Qt

like image 431
Sijith Avatar asked Dec 12 '25 07:12

Sijith


1 Answers

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 !

like image 157
Jérôme Avatar answered Dec 15 '25 23:12

Jérôme