天使羊波波闪耀光芒 软件及互联网爱好者

252月/170

C语言北京时间转为格林威治时间

北京时间比格林威治早8个小时,思路是先将北京时间转换为距1970年1月1日0点的秒数,然后在转换成服务器本地时区的格林威治时间。

例子程序 gmttime.c:

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

int main(void)
{
printf("--------------\n");
char ori_time[14+1];
char tmp_year[4+1];
char tmp_month[2+1];
char tmp_day[2+1];
char tmp_hour[2+1];
char tmp_min[2+1];
char tmp_sec[2+1];
char sCurrentTime[15];
struct tm tmCurrentTime, *gmCurrentTime;
time_t gmt;

memset(ori_time, 0x00, sizeof(ori_time));
memset(tmp_year, 0x00, sizeof(tmp_year));
memset(tmp_month, 0x00, sizeof(tmp_month));
memset(tmp_day, 0x00, sizeof(tmp_day));
memset(tmp_hour, 0x00, sizeof(tmp_hour));
memset(tmp_min, 0x00, sizeof(tmp_min));
memset(tmp_sec, 0x00, sizeof(tmp_sec));
memset(sCurrentTime, 0x00, sizeof(sCurrentTime));

memcpy(ori_time, "20170225132901", 14);
printf("ori_time: %s\n", ori_time);

//取年
memcpy(tmp_year, ori_time, 4);
printf("year: %s\n", tmp_year);
tmCurrentTime.tm_year = atoi(tmp_year);
tmCurrentTime.tm_year = tmCurrentTime.tm_year - 1900;
//取月
memcpy(tmp_month, ori_time+4, 2);
printf("month: %s\n", tmp_month);
tmCurrentTime.tm_mon = atoi(tmp_month);
tmCurrentTime.tm_mon = tmCurrentTime.tm_mon - 1;
//取日
memcpy(tmp_day, ori_time+6, 2);
printf("day: %s\n", tmp_day);
tmCurrentTime.tm_mday = atoi(tmp_day);
//取时
memcpy(tmp_hour, ori_time+8, 2);
printf("hour: %s\n", tmp_hour);
tmCurrentTime.tm_hour = atoi(tmp_hour);
//取分
memcpy(tmp_min, ori_time+10, 2);
printf("min: %s\n", tmp_min);
tmCurrentTime.tm_min = atoi(tmp_min);
//取秒
memcpy(tmp_sec, ori_time+12, 2);
printf("sec: %s\n", tmp_sec);
tmCurrentTime.tm_sec = atoi(tmp_sec);
//转换为秒
gmt = mktime(&tmCurrentTime); //time_t 转换为 tm
//转换为格林威治时间
gmCurrentTime = gmtime(&gmt); //tm 转换为 time_t
sprintf(sCurrentTime, "%4d%02d%02d%02d%02d%02d",
gmCurrentTime->tm_year + 1900, gmCurrentTime->tm_mon + 1,
gmCurrentTime->tm_mday, gmCurrentTime->tm_hour,
gmCurrentTime->tm_min, gmCurrentTime->tm_sec);
printf("gmt_time: %s\n", sCurrentTime);

printf("--------------\n");
return 0;
}

其中mktime将时间转换为秒数,gmtime将秒数转换为服务器本地时区对应的格林威治时间。

评论 (0) 引用 (0)

还没有评论.


Leave a comment

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!:

还没有引用.