Determine Number of Days into the year

For a project I needed to read data from EEPROM for every different day of the year. Using the day of the year from 1-365 as an index to read the memory seemed the easiest way. My RTClib library (from Adafruit) sadly didnt know a ‘day of the year’ function So I set out to make or find one. I came across a site where this was undertaken, but sadly that had a flaw that was probably not noticed by the owner because he only used it to determine if a day was even or odd. It gave me a good start though.
It entails altering the RTClib.h and RTClib.cpp files from the Adafruit RTC library.
First take the RTClib.h file and add the line as shown below:
Then open the RTClin.cpp file and add the function as shown below.
rtclibcppThis function cycles through an Array of ‘number of days per month’ stored in Flashram with PROGMEM. It starts by determining the current day and then add the days in the months from january till the current month to it.
Then it determines if february already passed and checks if it is a leapyear. If so it adds an extra day.
To use the function: define, initialize and start the RTC as usual. The call to “now.dayOfYear()” returns the number of days into the year.
e.g. Serial.print(now.dayOfYear();

The function is  m.m.somewhat  akin to the ‘days since 1-1-2000’ in the lib.

This function will work up to 2100 because that year is not a leap year (centuries as arule are not leap years). I could correct for that but then I also would have to correct for the year 2400 as that ís a leap year again (centuries are no leap years… unless the century is a multitude of 400).

2 thoughts on “Determine Number of Days into the year”

  1. There is a small error in your function, though irrelevant for the lifetime of this project I guess. Century years (yOff % 100 == 0) are no leap years UNLESS it is on a 400 year boundary (yOff % 400 == 0), in which case it IS a leap year. 2000 was a leap year for that reason 🙂

    1. You are totally correct, I thought about implementing it but as we are past 2000 I wasnt really too worried about 2100 😉 If anybody by that time gets in trouble for using my function they may sue me 😉

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.