rendered paste body#include <stdbool.h>
#include <avr/pgmspace.h>
#define SecondsInYear 31536000
struct DateTime
{
unsigned char Second;
unsigned char Minute;
unsigned char Hour;
unsigned char Day;
unsigned char Month;
unsigned int Year;
};
unsigned char months_of_year[] = {31,28,31,30,31,30,31,31,30,31,30,31};
inline bool IsLeapYear(int year);
int NumberOfDaysTillNow(int year, unsigned char month, unsigned char day);
//Time DateAdd(time startTime, unsigned long long ticks);
inline bool IsLeapYear(int year)
{
if (year % 4 != 0)
return false;
else if (year % 400 == 0)
return true;
else if (year % 100 == 0)
return false;
else
return true;
}
inline int NumberOfDaysInTheYear(int year)
{
return(IsLeapYear(year))? 366 : 365;
}
unsigned long NumberOfSecondsTillNow(struct DateTime dateTime)
{
//Add months
unsigned long i,sum=0;
for (i=0;i<dateTime.Month-1;i++)
{
sum+= months_of_year[i] * 86400;
}
//add leap day if neccesary.
sum+= dateTime.Day;
if(IsLeapYear(dateTime.Year) && dateTime.Month>2)
sum+=86400;
sum += (dateTime.Hour * 3600); //Add hours
sum += (dateTime.Minute * 60); //Add minutes
sum += dateTime.Second; //Add Seconds
return sum;
}
unsigned long DateTimeToEpochSeconds(struct DateTime startTime)
{
unsigned long result = 0;
//Days from start of startTime.Year
unsigned long overFlowSeconds = NumberOfSecondsTillNow(startTime);
//Roll back year to 1970
while(startTime.Year > 1970)
{
if(IsLeapYear(startTime.Year) == true)
result += (SecondsInYear + 86400); //add year
else
result += SecondsInYear;
startTime.Year--;
}
//Remaining seconds in second
result += overFlowSeconds;
return result;
}
struct DateTime EpochSecondsToDateTime(unsigned long epochSeconds)
{
struct DateTime dateTime;
dateTime.Year = 1970;
}