2010-05-21 105 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;