Home > Blockchain >  How to convert day of week from Sunday first to Monday first in c ?
How to convert day of week from Sunday first to Monday first in c ?

Time:04-18

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.

CodePudding user response:

Alternative:

To map 0...6 from [Sun. to Sat.] to [Mon. to Sun.]

dayOfWeek_fromMonday = (dayOfWeek_fromSunday   6)%7;

CodePudding user response:

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;

CodePudding user response:

No need for double negatives:-

int const dayOfWeek = currTime.dayOfTheWeek() ?
     currTime.dayOfTheWeek() - 1
     :
     6;
  • Related