【原创】C++中时间格式的转换 tm

来源:互联网 发布:ubuntu卸载输入法 编辑:程序博客网 时间:2024/05/29 12:13

struct tm * local;/// 时间格式 2011-09-10-22-30-15

time_t t;/// 时间 LONGLONG 是距离1970年1月1日的时间

time(&t);

local = localtime(&t);/// 当前系统时间

printf("Local year is: %d\n",local->tm_year+1900);/// 时间格式中的年份为 +1900 为现在的年份

printf("Local month is: %d\n",local->tm_mon+1);/// 月份为0、1、2、3、4、5、6、7、8、9、10、11

printf("Local day is: %d\n",local->tm_mday);

printf("Local hour is: %d\n",local->tm_hour);

printf("Local minute is: %d\n",local->tm_min);

printf("Local second is: %d\n",local->tm_sec);


local = gmtime(&t);
printf("UTC hour is: %d\n" , local->tm_hour);

char str[256] = {0};
strftime( str, 128, "Today is%A, day %d of%B in the year %Y.\n",local);/// 通过tm格式可以直接得到 年 月 日
cout<<str<<endl;


time_t tTimea = StringToStructTime("2011-09-10-22-30-15");
int chargeTime = 20;
tTimea +=chargeTime;
struct tm *tTime;
tTime = localtime(&tTimea);
printf("Local year is: %d\n",tTime->tm_year+1900);
printf("Local month is: %d\n",tTime->tm_mon+1);
printf("Local day is: %d\n",tTime->tm_mday);
printf("Local hour is: %d\n",tTime->tm_hour);
printf("Local minute is: %d\n",tTime->tm_min);
printf("Local second is: %d\n",tTime->tm_sec);


char strTime[24] = {0};
sprintf_s(strTime, "%4d-%2d-%2d-%2d-%2d-%2d", tTime->tm_year+1900,tTime->tm_mon+1,tTime->tm_mday,tTime->tm_hour,tTime->tm_min,tTime->tm_sec);
cout<<strTime<<endl;


system("pause");


/// end main



time_t StringToStructTime(char * szTime)
{
struct tm tm1;


time_t time1;


sscanf(szTime, "%4d-%2d-%2d-%2d-%2d-%2d",&tm1.tm_year, &tm1.tm_mon, &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min,&tm1.tm_sec);


tm1.tm_year -= 1900;
tm1.tm_mon --;
tm1.tm_isdst = -1;


time1 = mktime(&tm1);
return time1;
}