字符串转时间(time_t)

#include <stdio.h>
#include <time.h>
/**
 *      str为日期字符串
 *      formatStr 为时间对应的格式,
 *      如2012-07-04 15:33:52对应的格式为%d-%d-%d %d:%d:%d
 */
time_t string2time(const char * str,const char * formatStr)
{
  struct tm tm1;
  int year,mon,mday,hour,min,sec;
  if( -1 == sscanf(str,formatStr,&year,&mon,&mday,&hour,&min,&sec)) return -1;
  tm1.tm_year=year-1900;
  tm1.tm_mon=mon-1;
  tm1.tm_mday=mday;
  tm1.tm_hour=hour;
  tm1.tm_min=min;
  tm1.tm_sec=sec;
  return mktime(&tm1);
}
int main(void) {
  time_t t1=string2time("2012-07-04 15:33:52","%d-%d-%d %d:%d:%d");
  if(t1 == -1)
    {
      fputs("convert error!\n",stderr);
      exit(1);
    }
  char buf[20]={0};
  strftime(buf,sizeof(buf),"%F %T",localtime(&t1));
  printf("%s\n",buf);
  return 0;
}

你可能感兴趣的:(struct,String,include)