69,369
社区成员
发帖
与我相关
我的任务
分享
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
#include <stdint.h>
#define STR_TO_INT(x) strtoul(x, 0, 10)
int check_time(char **str1, uint64_t *ret)
{
int len, i;
char *p, p1[5];
time_t tmt;
struct tm t;
char *str = *str1;
char tmp[15];
if (str == NULL)
{
*ret = 0;
return 0;
}
len = strlen(str);
if (len > 14) /* YYYYMMDDhhmmss */
{
str[14] = 0;
len = strlen(str);
}
for (i=0; i<len; i++)
{
if ((str[i] < '0') || (str[i] > '9'))
return -1;
}
strncpy(tmp, str, 14);
for (i=len; i<14; i++)
{
tmp[i]='0';
}
tmp[14] = '\0';
p = tmp;
memcpy(p1, p, 4);
p1[4]=0;
p += 4;
t.tm_year = STR_TO_INT(p1);
if (t.tm_year<=1900)
t.tm_year = 1900;
t.tm_year -= 1900;
memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_mon = STR_TO_INT(p1);
if (t.tm_mon == 0)
t.tm_mon = 1;
else if (t.tm_mon > 12)
return -1;
t.tm_mon -= 1;
memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_mday = STR_TO_INT(p1);
if (t.tm_mday == 0)
t.tm_mday = 1;
else if (t.tm_mday > 31)
return -1;
memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_hour = STR_TO_INT(p1);
if (t.tm_hour>23)
return -1;
memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_min = STR_TO_INT(p1);
if (t.tm_min>59)
return -1;
memcpy(p1, p, 2);
p1[2]=0;
p += 2;
t.tm_sec = STR_TO_INT(p1);
if (t.tm_sec>59)
return -1;
t.tm_isdst = 0;
printf("%d\n",t.tm_isdst);
printf("%d-%d-%d %d:%d:%d\n",t.tm_year, t.tm_mon, t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
tmt = mktime(&t);
printf("%llu\n", tmt);
localtime_r(&tmt, &t);
printf("%d-%d-%d %d:%d:%d\n",t.tm_year, t.tm_mon, t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
*ret = tmt*1000;
return 0;
}
int main(int argc, char ** argv)
{
uint64_t t;
check_time(&argv[1], &t);
printf("t=%llu\n", t);
return 0;
}