miércoles, 28 de abril de 2010

doy2tm.c


#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

time_t doy2tm(const int year, const int dayofyear, struct tm *tm) {

int leapyear, m, d;

int d_in_m [] = {31,28,31,30,31,30,31,31,30,31,30,31};

memset(tm, 0, sizeof(*tm));

leapyear = (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));

if( dayofyear < 1 || dayofyear > (leapyear ? 366 : 365) ) {
return (time_t) -1;
}

if(leapyear) { d_in_m[1]=29; }

for(m=0, d=dayofyear;
d>d_in_m[m];
d-=d_in_m[m++]);

tm->tm_mday=d;
tm->tm_mon=m;
tm->tm_year=year - 1900;

return mktime(tm);
}

int main (int argc, char* argv[]) {
struct tm tm;
int y,d;
char str[128];

if (argc != 3) {
fprintf(stderr, "Usage: %s year dayofyear\n", argv[0]);
return EXIT_FAILURE;
}

y = atoi(argv[1]);
d = atoi(argv[2]);

if (doy2tm(y,d,&tm) == -1) {
fputs("doy2tm returned -1\n", stderr);
return EXIT_FAILURE;
}

if (strftime(str, sizeof(str), "%c", &tm) == 0) {
fputs("strftime returned 0\n", stderr);
return EXIT_FAILURE;
}

printf("%d %d => %s\n", y, d, str);
return EXIT_SUCCESS;
}

No hay comentarios.: