Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Epoch to time algorithm

Tags: epoch


#include <stdio.h>
#include <stdlib.h>

int is_leap(int year)
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

}
int days_in_month[] = {
[ 0 ] = 31,
[ 1 ] = 28,
[ 2 ] = 31,
[ 3 ] = 30,
[ 4 ] = 31,
[ 5 ] = 30,
[ 6 ] = 31,
[ 7 ] = 31,
[ 8 ] = 30,
[ 9 ] = 31,
[ 10 ] = 30,
[ 11 ] = 31,
};


int main(void)
{
long year = 1970;
long month = 0;
long day= 0;
long hour= 0;
long minute= 0;
long epoch = 1372182691;

do {
int nb_days = 365;
if (is_leap(year)) {
nb_days += 1;
}
if (epoch >= nb_days * 24 * 3600) {
epoch -= nb_days * 24 * 3600;
year++;
continue;
}
do {
int dim = days_in_month[month];
if (is_leap(year) && month == 1) {
dim++;
}
if (epoch >= dim * 24 * 3600) {
epoch -= dim * 24 * 3600;
month++;
continue;
}
while (epoch >= 24 * 3600) {
epoch -= 24 * 3600;
day++;
}
while (epoch >= 3600) {
epoch -= 3600;
hour++;
}
while (epoch >= 60) {
epoch -= 60;
minute++;
}
goto out;
} while (1);
abort();
} while (1);
out:
fprintf(stderr, "%ld %ld %ld %ld %ld\n", year, month + 1, day + 1, hour, minute);
return 1;
}


This post first appeared on Tail -f /dev/random, please read the originial post: here

Share the post

Epoch to time algorithm

×

Subscribe to Tail -f /dev/random

Get updates delivered right to your inbox!

Thank you for your subscription

×