0

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.

Sigur
  • 355
  • 8
  • 19
  • What have you tried so far? – Nick Jul 14 '18 at 16:21
  • @Nick In my case, Friday is 5th day of week. So I tried to test if `Mydate.dayOfWeek()` is `5` or not. Then, I got lost when `Mydate.day()` is greater than the first Friday (like today, 14). I was not able to decide when stop subtracting from `14`. – Sigur Jul 14 '18 at 16:27

2 Answers2

2

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
Sigur
  • 355
  • 8
  • 19
Nick
  • 4,820
  • 18
  • 31
  • 47
1

Adding to Nick's answer, there needs to be a special case where result of MyDate.day() - dayOfWeekToday + 5 is divisible by 7. Something like:

dayOfWeekToday = MyDate.dayOfWeek()
firstFriday = MyDate.day() - dayOfWeekToday + 5
firstFriday = (firstFriday <= 0) ? firstFriday + 7 
                                 : (firstFriday % 7 == 0) ? 7 : firstFriday % 7
  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30280270) – Alex Guteniev Nov 07 '21 at 19:24