c - Convert unix timestamp to date without system libs -


i building embedded project displays time retrieved gps module on display, display current date. have time unix time stamp , progject written in c.

i looking way calculate current utc date timestamp, taking leap years account? remember, embedded project there no fpu, floating point math emulated, avoiding as possible performance required.

edit

after looking @ @r...'s code, decided have go writing myself , came following.

void calcdate(struct tm *tm) {   uint32_t seconds, minutes, hours, days, year, month;   uint32_t dayofweek;   seconds = gpsgetepoch();    /* calculate minutes */   minutes  = seconds / 60;   seconds -= minutes * 60;   /* calculate hours */   hours    = minutes / 60;   minutes -= hours   * 60;   /* calculate days */   days     = hours   / 24;   hours   -= days    * 24;    /* unix time starts in 1970 on thursday */   year      = 1970;   dayofweek = 4;    while(1)   {     bool     leapyear   = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));     uint16_t daysinyear = leapyear ? 366 : 365;     if (days >= daysinyear)     {       dayofweek += leapyear ? 2 : 1;       days      -= daysinyear;       if (dayofweek >= 7)         dayofweek -= 7;       ++year;     }     else     {       tm->tm_yday = days;       dayofweek  += days;       dayofweek  %= 7;        /* calculate month , day */       static const uint8_t daysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};       for(month = 0; month < 12; ++month)       {         uint8_t dim = daysinmonth[month];          /* add day feburary if leap year */         if (month == 1 && leapyear)           ++dim;          if (days >= dim)           days -= dim;         else           break;       }       break;     }   }    tm->tm_sec  = seconds;   tm->tm_min  = minutes;   tm->tm_hour = hours;   tm->tm_mday = days + 1;   tm->tm_mon  = month;   tm->tm_year = year;   tm->tm_wday = dayofweek; } 

first divide 86400; remainder can used trivially hh:mm:ss part of result. now, you're left number of days since jan 1 1970. adjust constant number of days (possibly negative) since mar 1 2000; because 2000 multiple of 400, leap year cycle, making easy (or @ least easier) count how many leap years have passed using division.

rather trying explain in more detail, i'll refer implementation:

http://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c?h=v0.9.15


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -