pezy
3/28/2014 - 2:25 AM

many date&time format function(use sscanf)

many date&time format function(use sscanf)

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

int map_month_name(char const *mmm)
{
    static char const *months[] =
    {
        "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
    };
    for (size_t i = 0; i < sizeof(months)/sizeof(months[0]); i++)
    {
        if (strcmp(mmm, months[i]) == 0)
            return i + 1;
    }
    return -1;
}

int main ()
{
  char sentence []="25-JUL-2002,09:28:22";
  char day[2], mon[3], hour[2], min[2], sec[2];
  int d,y,h,m,s;

  sscanf (sentence,"%[^-]-%[^-]-%i,%[^:]:%[^:]:%s",day, mon, &y, hour, min, sec);
  d = atoi(day);
  h = atoi(hour);
  m = atoi(min);
  s = atoi(sec);
  printf ("%04i-%02i-%02i %02i:%02i:%02i\n", y, map_month_name(mon), d, h, m, s);
  
  return 0;
}