mktime 返回1970年1月1日的秒数,和当前本地设置的时区相关
日期遇到本地时区是美东时间,远端设置过来的时间是上海时间,再设置成utc时间,其中代码如下:
#include <time.h>
int g_timediff =8;
int btsSetTime(char* msgBuf)
{
char szTime[32];
char szCmd[32];
memset(szTime,0,32);
memset(szCmd,0,32);
strcpy(szTime, msgBuf);
struct tm tm_time;
strptime(szTime, "%Y.%m.%d-%H:%M:%S", &tm_time);
#if 1
setenv("TZ","Asia/Shanghai","1");
tzset();
#endif
time_t settime = mktime(&tm_time);
time_t curtime = settime - g_timediff*3600;
struct tm *lt;
lt = gmtime(&curtime);
strftime(szCmd, 32, "date -u -s %Y.%m.%d-%H:%M:%S", lt);
printf("time cmd : %s\n",szCmd);
system(szCmd);
return 0;
}
int main()
{
char szTime[32];
sprintf(szTime,"%s","2020.02.28-17:56:55");
btsSetTime(szTime);
return 0;
}这里插入代码片
还有一种方法是通过设置环境变量
TZ=CST+/-hhmm 或 hh:mm
如:
东8区设置;
export TZ=CST-8
或
export TZ=CST-0800
或
export TZ=CST-8:00
西830设置;
export TZ=CST+0830