//从字符串得到月的数字
char *g_months[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};
int getmonth(const char * m){
int y=0;
int x=0;
for(y=0;y<12;y++){
if(0==strncmp(g_months[y],m,strlen(m)) ){
printf("date m=%d\n",++y);
x=y;
break;
}
if(0==strncasecmp(g_months[y],m,strlen(m)) ){
printf("date ignore m=%d\n",++y);
x=y;
break;
}
}
return x;
}
调用函数得到结果
char m[8]={0};
scanf("%s",m);
mon=getmonth(m);
printf("月的值为:%d\n",mon);
如果是其他语言比如java,可能用枚举能更优雅的到结果,这里特别注意下c语言枚举结果是整形,不能用纯枚举实现,相当于多了几个整形的宏定义
enum MOUTH{ Jan=1 ,Feb,Mar,Apr,May,Jun,Jul,Aug,Sept,Oct,Nov,Dec};
enum MOUTH mon; /* 定义枚举类型 */
for(mon = Jan;mon <= Dec; mon++){ /* 循环遍历枚举类型中元素的值 */
printf("%d月的值为:%d\n",mon,mon);
}
得到当前时区与utc的时差 小时数
int diffmonth(){
int h1=0;
time_t t;
struct tm *gmt, *area;
tzset(); /*tzset()*/
t = time(NULL);
area = localtime(&t);
printf("Local time is: %s", asctime(area));
h1=area->tm_hour;
printf("hour is: %d \n",area->tm_hour);
gmt = gmtime(&t);
printf("GMT is: %s", asctime(gmt));
printf("gmt hour is: %d \n",gmt->tm_hour);
printf("hour diff is: %d %d diff=%d\n",h1,gmt->tm_hour, (h1- gmt->tm_hour));
return (h1-gmt->tm_hour);
}
输入utc,偏移后输出cst字符串 此处为了简化固定用时差8,如果其他时区可用上面函数 diffmonth
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE
#endif
long analyse_time( char* str_time, char* new_time)
{
struct tm stm;
memset(&stm, 0, sizeof(stm));
strptime(str_time, "%Y-%m-%d %H:%M:%S", &stm);
stm.tm_hour=stm.tm_hour+8;
//stm.tm_sec++;
long t = mktime(&stm);
struct tm tm2 = *localtime(&t);
strftime(new_time, 20, "%Y-%m-%d %H:%M:%S", &tm2);
printf("new_time= %s \n", new_time);
return 0;
}
strptime函数编译时有时候会报错,在gcc的编译命令后增加参数,比如如下makefile文件
duc1:duc1.c test_a.c
gcc -g test_a.c duc1.c -o duc1 -D _XOPEN_SOURCE