代码之家  ›  专栏  ›  技术社区  ›  Sijith

如何计算一个月内的周数

  •  2
  • Sijith  · 技术社区  · 15 年前

    我想计算本月的总周数。从星期日或星期一开始。 可以用qt做吗

    3 回复  |  直到 7 年前
        1
  •  3
  •   Jérôme    15 年前

    我想说这个问题不是针对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++;
    }
    

    此代码尚未经过全面测试,不允许使用!

        2
  •  3
  •   gvaish    15 年前
    floor(Number of Days / 7)
    
        3
  •  2
  •   scopchanov    7 年前

    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;