-2

I am making a Clock and I have got all the hardware figured out and I'm working on the software now. I have the exact date of a particular day, but I want the Arduino to be able to convert that into a day of the week. I have had a look online, but I can't seem to get any of the libraries to work. Does anyone have any easy to use code for this problem?

Elliot
  • 27
  • 4
  • 1
    a simple google will give lots of simple ways to calculate day of week right away https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto's_methods – phuclv Oct 06 '20 at 12:40
  • All of this depends on in which format you get the output from the external RTC. – Lundin Oct 06 '20 at 13:22

1 Answers1

4

You don't need a library for that, you can use Tomohiko Sakamoto's Algorithm based on offsets:

/**
 * Sunday = 0 ... Saturday = 6
 */
int day_of_week(int day, int month, int year)
{
    static const int offset[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};

    year -= month < 3;
    return (year + year / 4 - year / 100 + year / 400 + offset[month - 1] + day) % 7;
}

or if you prefer:

/**
 * ISO 8601 date and time standard
 * Monday = 1 ... Sunday = 7
 */
int ISO_day_of_week(int day, int month, int year)
{
    static const int offset[] = {6, 2, 1, 4, 6, 2, 4, 0, 3, 5, 1, 3};

    year -= month < 3;
    return (year + year / 4 - year / 100 + year / 400 + offset[month - 1] + day) % 7 + 1;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    Notably, this code will execute godawfully slow on AVR. One of the few things it hates more than division is 16 or 32 bit integers. Switch all types involved to `uint8_t` where possible, then split the algorithm up in multiple lines. It's not a PC. – Lundin Oct 06 '20 at 13:20