2010-05-21 71 views
2

我想計算當月的總週數。從週日或週一開始。 是否有可能在Qt的如何計算一個月中的週數

+0

@sijith什麼手段*當月總週數*?什麼是IN和什麼是OUT? – mosg 2010-05-21 06:23:02

回答

3

我會說這個問題不是特定於Qt的做,但Qt可以幫助你的QDate類。 有了這個類,你可以得到當前的月份:

QDate CurrentDate = QDate::currentDate(); 

某月的天數:

CurrentDate.daysInMonth(); 

對於週數計算,這取決於如果只想數量一個月中的整週,或週數,考慮部分周。

對於後者,這裏是我會怎麼做(考慮到本週週一開始):

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++; 
} 

此代碼沒有經過完全測試,並且不保證下,工作!

3
floor(Number of Days/7) 
0

在闡述的xfakehopex答案,這裏是如何使用QDate::weekNumber獲得周在一個月內包括短於七天數爲例:

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;