Imagine you can't use the standard functions for time calculation or anything alike. You have to start from scratch as it is the case on embedded systems.
Thus I came with the following code to determine the seconds, minutes, hours, days, months and years from unix timestamp. Tested the code, works for everything I threw at it so far, but wonder if there is a better way to do it without using the standard functions
#include <iostream>
int main(int argc, char* argv[])
{
/* Subtract 2 years to start on leaping year, later add 1972 instead. */
auto now = std::atoi(argv[1]) - 63072000;
auto days = (now / 86400);
auto hours = (((now - days * 86400) / 3600) % 24);
auto minutes = ((((now - days * 86400) - hours * 3600) / 60) % 60);
auto seconds = (((((now - days * 86400) - hours * 3600) - minutes * 60)) % 60);
/* Get number of 4years to accomodate for leap years */
auto q_years = (days / 1461);
/* Recalculate the number of years */
auto years = q_years * 4 + (days - (q_years * 1461)) / 365;
/* Deterimne no. of days in the current year */
auto days_last = (days - (q_years * 1461)) % 365;
static uint8_t days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/* Fix for leap year */
if (years % 4 == 0)
{
days_in_month[1] = 29;
days_last++;
}
/* Retrace current month */
int month = 0;
while (days_last > days_in_month[month])
{
days_last -= days_in_month[month++];
}
printf("Year: %d, Month: %d\n", 1972 + years, month + 1);
printf("Days: %d, Hours: %d, Minutes: %d, Seconds:%d\n", days_last, hours, minutes, seconds);
return 0;
}
yes, the code is in c++ but I'll be rewriting it to C afterwards - basically letting go of auto.
What I am not looking at is code readability error checking (what if argv does not have 2 el.) et cetra. I am purely looking for a better algo to get the job done.