Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <time.h>
- typedef uint32_t _u32;
- typedef struct
- {
- /* time */
- _u32 sl_tm_sec;
- _u32 sl_tm_min;
- _u32 sl_tm_hour;
- /* date */
- _u32 sl_tm_day; /* 1-31 */
- _u32 sl_tm_mon; /* 1-12 */
- _u32 sl_tm_year; /* YYYY 4 digits */
- _u32 sl_tm_week_day; /* not required */
- _u32 sl_tm_year_day; /* not required */
- _u32 reserved[3];
- } SlDateTime_t;
- #define DAY 86400
- #define YEAR (DAY * 365)
- #define YEAR4 (YEAR * 4 + DAY)
- static int secs2tm(time_t t, SlDateTime_t *st)
- {
- /* days in a month, starting March */
- uint8_t dom[] = { 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29 };
- int i;
- /* start just after 29 Feb 1972, the first leap day in the UNIX history*/
- st->sl_tm_year = 1972;
- t -= 68256000;
- if (t > YEAR4) {
- st->sl_tm_year += t / YEAR4 * 4;
- t %= YEAR4;
- }
- if (t > YEAR) {
- st->sl_tm_year += t / YEAR;
- t %= YEAR;
- dom[11]--;
- }
- for (i = 0; i < 11; i++) {
- if(t < DAY * dom[i])
- break;
- t -= DAY * dom[i];
- }
- st->sl_tm_mon = i + 3;
- if (st->sl_tm_mon > 12) {
- st->sl_tm_year++;
- st->sl_tm_mon -= 12;
- }
- st->sl_tm_day = t / DAY + 1;
- t %= DAY;
- st->sl_tm_hour = t / 3600;
- t %= 3600;
- st->sl_tm_min = t / 60;
- t %= 60;
- st->sl_tm_sec = t;
- return 0;
- }
- /*
- test with:
- while : ; do
- d=$RANDOM$RANDOM
- [ $d -lt 68256000 ] && continue
- [ "$(./s2t $d)" = "$(date -u -d"@$d" +"%F %T")" ] || echo "error @$d: $(./s2t $d) != ($(date -u -d"@$d" +"%F %T"))"
- done
- */
- int main(int argc, char *argv[])
- {
- SlDateTime_t tm;
- uint32_t date;
- if(argc < 2) {
- fprintf(stderr, "usage: %s <secs from epoch>\n", *argv);
- return 1;
- }
- date = atoi(argv[1]);
- secs2tm(date, &tm);
- printf("%04u-%02u-%02u %02u:%02u:%02u\n",
- tm.sl_tm_year,
- tm.sl_tm_mon,
- tm.sl_tm_day,
- tm.sl_tm_hour,
- tm.sl_tm_min,
- tm.sl_tm_sec
- );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement