calendar/date maths - do any of the existing libraries do this well?


I’ve been looking at the Adafruit RTC library, the Arduino Time library and associated TimeAlarms library but none of these directly helps.

What I’m wanting to do is to choose an arbitrary period, add it to the current date and feed this into a variable (of DateTime or time_t etc) such that the month, year etc rollovers are taken account of. If I do this with the Adafruit library for example

    now = DateTime(ayear, amonth, aday, ahour, aminute, asecond);

it will be quite happy to increment the day value out to the 100th of the month and beyond without complaining, so adding 7 to the day to construct a variable containing 5pm on the same day in a weeks’ time can’t be done this way (though curiously the unixtime() returned does appear to be correct, so it’s possible I could reverse it back from that).

I’m happy to code around this, but thought it best first to check if it’s already present somewhere.


If you hold the current date and time in the same format as time_t, or convert to it when you need to, then you can add an arbitrary period to it in the same format and rollovers will be taken care of, won't they ?

The Time library has functions to convert back and forth between time_t format and individual time elements.

Thanks Bob - sometimes I can’t see past my nose.

void breakTime(time_t time, tmElements_t &tm);  // break time_t into elements
time_t makeTime(tmElements_t &tm);  // convert time elements into time_t

There was my answer right there. And, no 100th February 2013 now :slight_smile:

#include <Time.h>
  tmElements_t tmE;
  time_t atime;

void setup() {
  tmE.Second = 00;
  tmE.Minute = 00;
  tmE.Hour = 00;
  tmE.Day = 28;
  tmE.Month = 01;
  tmE.Year = 43;

void loop() {
  atime = makeTime(tmE);
  Serial.print(" ");
  Serial.print(", ");
  Serial.print (" is a ");

results in

29 1, 2013 is a Tuesday
30 1, 2013 is a Wednesday
31 1, 2013 is a Thursday
1 2, 2013 is a Friday
2 2, 2013 is a Saturday
3 2, 2013 is a Sunday
4 2, 2013 is a Monday

Thanks for the nudge in the right direction,

It depends what "arbitrary period" you are concerned with ?

The seventeenth century ?

Dates after 2099 ?

Otherwise, it's very simple.