So geht es mit Unix Time. Aus der Time Library geklaut und etwas angepasst:
#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
#define SECS_PER_MIN (60UL)
#define SECS_PER_HOUR (3600UL)
#define SECS_PER_DAY (SECS_PER_HOUR * 24UL)
const uint8_t monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
struct tm_t
{
uint8_t Second;
uint8_t Minute;
uint8_t Hour;
uint8_t Wday;
uint8_t Day;
uint8_t Month;
uint16_t Year;
};
void unixToDate(uint32_t unixtime, struct tm_t& tm)
{
uint8_t year, month, monthLength;
uint32_t days;
tm.Second = unixtime % 60;
unixtime /= 60;
tm.Minute = unixtime % 60;
unixtime /= 60;
tm.Hour = unixtime % 24;
unixtime /= 24;
tm.Wday = ((unixtime + 4) % 7) + 1;
year = 0;
days = 0;
while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= unixtime) {
year++;
}
tm.Year = year;
days -= LEAP_YEAR(year) ? 366 : 365;
unixtime -= days;
days=0;
month=0;
monthLength=0;
for (month=0; month<12; month++) {
if (month==1) {
if (LEAP_YEAR(year)) {
monthLength=29;
} else {
monthLength=28;
}
} else {
monthLength = monthDays[month];
}
if (unixtime >= monthLength) {
unixtime -= monthLength;
} else {
break;
}
}
tm.Year += 1970;
tm.Month = month + 1;
tm.Day = unixtime + 1;
}
uint32_t dateToUnix(struct tm_t& tm)
{
unsigned int i;
uint32_t seconds;
tm.Year -= 1970;
seconds = tm.Year*(SECS_PER_DAY * 365);
for (i = 0; i < tm.Year; i++) {
if (LEAP_YEAR(i)) {
seconds += SECS_PER_DAY;
}
}
for (i = 1; i < tm.Month; i++) {
if ( (i == 2) && LEAP_YEAR(tm.Year)) {
seconds += SECS_PER_DAY * 29;
} else {
seconds += SECS_PER_DAY * monthDays[i-1];
}
}
seconds+= (tm.Day-1) * SECS_PER_DAY;
seconds+= tm.Hour * SECS_PER_HOUR;
seconds+= tm.Minute * SECS_PER_MIN;
seconds+= tm.Second;
return seconds;
}
void printDate(struct tm_t& tm)
{
Serial.print(tm.Day); Serial.print('/'); Serial.print(tm.Month); Serial.print('/'); Serial.println(tm.Year);
Serial.print(tm.Hour); Serial.print(':'); Serial.print(tm.Minute); Serial.print(':'); Serial.println(tm.Second);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
tm_t tm;
tm.Day = 27;
tm.Month = 6;
tm.Year = 1971;
tm.Hour = 12;
tm.Minute = 31;
tm.Second = 25;
printDate(tm);
unsigned long time = dateToUnix(tm);
Serial.println(time);
Serial.println();
time = time - 7 * SECS_PER_DAY;
Serial.println(time);
unixToDate(time, tm);
printDate(tm);
Serial.println();
delay(5000);
}
Es gibt auch einfachere Algorithmen, aber nicht alles was man im Netz (vor allem in Foren) findet geht auch