首页 > 代码库 > time_t与GMT格式互转
time_t与GMT格式互转
time_t Time::timeFromGMT(string gmt)
{
char week[4];
memset(week,0,4);
char month[4];
memset(month,0,4);
tm date;
sscanf(gmt.c_str(),"%3s, %2d %3s %4d %2d:%2d:%2d GMT",week,&date.tm_mday,month,&date.tm_year,&date.tm_hour,&date.tm_min,&date.tm_sec);
date.tm_mon = getMonthByName(month);
date.tm_wday = getWeekDayByName(week);
date.tm_year = date.tm_year - 1900;
return mktime(&date);
}
string Time::GMTStrFromTime(time_t time)
{
char gmt[40];
memset(gmt,0,40);
tm* date = localtime(&time);
sprintf(gmt,"%3s, %2d %3s %4d %02d:%02d:%02d GMT",getWeekDayName(date->tm_wday).c_str(),date->tm_mday,getMonthName(date->tm_mon).c_str(),date->tm_year+1900,date->tm_hour,date->tm_min,date->tm_sec);
return string(gmt);
}
/**
* @brief [0-11]表示1到12月
* @param month
* @return
*/
int Time::getMonthByName(char* month)
{
if(strcmp(month,"Jan") == 0)
return 0;
if(strcmp(month,"Feb") == 0)
return 1;
if(strcmp(month,"Mar") == 0)
return 2;
if(strcmp(month,"Apr") == 0)
return 3;
if(strcmp(month,"May") == 0)
return 4;
if(strcmp(month,"Jun") == 0)
return 5;
if(strcmp(month,"Jul") == 0)
return 6;
if(strcmp(month,"Aug") == 0)
return 7;
if(strcmp(month,"Sep") == 0)
return 8;
if(strcmp(month,"Oct") == 0)
return 9;
if(strcmp(month,"Nov") == 0)
return 10;
if(strcmp(month,"Dec") == 0)
return 11;
return -1;
}
/**
* @brief [0-11]表示1到12月
* @param month
* @return
*/
string Time::getMonthName(int month)
{
switch(month)
{
case 0:return "Jan";
case 1:return "Feb";
case 2:return "Mar";
case 3:return "Apr";
case 4:return "May";
case 5:return "Jun";
case 6:return "Jul";
case 7:return "Aug";
case 8:return "Sep";
case 9:return "Oct";
case 10:return "Nov";
case 11:return "Dec";
default:return " ";
}
}
/**
* @brief [0-6]表示周日到周六
* @param wday
* @return
*/
int Time::getWeekDayByName(char* wday)
{
if(strcmp(wday,"Sun") == 0)
return 0;
if(strcmp(wday,"Mon") == 0)
return 1;
if(strcmp(wday,"Tue") == 0)
return 2;
if(strcmp(wday,"Wed") == 0)
return 3;
if(strcmp(wday,"Thu") == 0)
return 4;
if(strcmp(wday,"Fri") == 0)
return 5;
if(strcmp(wday,"Sat") == 0)
return 6;
return -1;
}
/**
* @brief [0-6]表示周日到周六
* @param wday
* @return
*/
string Time::getWeekDayName(int wday)
{
switch(wday)
{
case 1:return "Mon";
case 2:return "Tue";
case 3:return "Wed";
case 4:return "Thu";
case 5:return "Fri";
case 6:return "Sat";
case 0:return "Sun";
default:return " ";
}
}
time_t与GMT格式互转