'How to convert day of week from Sunday first to Monday first in c++?
I have a function which returns the day of week as an integer, Sunday = 0, Monday = 1, etc. to 6. I want to convert this to Monday = 0, ..., Sunday = 6. I can not think of better way than the one listed below, but it is clumsy. Is there a better way?
if (!currTime.dayOfTheWeek()) { // if time.dow == 0
dayOfWeek = 6;
}
else {
dayOfWeek = currTime.dayOfTheWeek() - 1;
}
by the way, this is Arduino code, using RTCLib for time.
Solution 1:[1]
Alternative:
To map 0...6 from [Sun. to Sat.] to [Mon. to Sun.]
dayOfWeek_fromMonday = (dayOfWeek_fromSunday + 6)%7;
Say you wanted to start on Wednesday (something more interesting that a shift by 1) rather than Sunday and avoid naked magic numbers.
#define DaysWedToSun 4
#define DaysPerWeek 7
dayOfWeek_fromWed = (dayOfWeek_fromSun + DaysWedToSun)%DaysPerWeek;
Solution 2:[2]
Keep it simple. What are the rules? If the day is Sunday(0) we change it to 6, all others we subtract one.
int dayOfWeek = ..;
dayOfWeek = dayOfWeek == 0 ? 6 : dayOfWeek - 1;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | gnasher729 |
