qtqdate

How to obtain first Friday from a given QDate?


Consider a Qdate from

QDate Mydate = ui->dateEdit->date();

For example, suppose we choose 2018/07/14 (today).

How to obtain the day of the first Friday (in this case, 6) on the chosen month (in this case, July)?

I suspect we have to use Mydate.dayOfWeek() computations.


Solution

  • There is probably a neater solution, but:

    1. Subtract dayOfWeek for current date/day from dayOfMonth.
    2. Add 5 (for Friday).
    3. If -ve add 7 or if +ve answer is modulus 7.

    Code:

    dayOfWeekToday = MyDate.dayOfWeek()
    firstFriday = MyDate.day() - dayOfWeekToday + 5
    firstFriday = (firstFriday <= 0) ? firstFriday + 7 : firstFriday % 7