zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ 时间戳转本地时间 函数

C++ 函数 时间 本地
2023-09-14 09:07:02 时间

时间戳转本地时间在网上找了一上午,中午研究出来一个,同时进行了一些改进。

.h文件

//时间戳转本地时间。returnType=0,返回年月日时分秒,returnType=1,返回年月日,returnType=2,返回时分秒。time_t 单位是秒。

std::string TimestampToTimeString(time_t t, int nType=0);

.cpp文件

//时间戳转本地时间。returnType=0,返回年月日时分秒,returnType=1,返回年月日,returnType=2,返回时分秒。time_t 单位是秒。
std::string TimestampToTimeString(time_t t, int nType)
{

t = t + 28800;//偏移八个时区
struct tm *p;
char s[32];
std::string strTime;
p = gmtime(&t);
switch (nType)
{
case 0:
{
strftime(s, 32, "%Y-%m-%d %H:%M:%S", p);
strTime = s;
}
break;
case 1:
{
    strftime(s, 32 ,"%Y-%m-%d", p);
strTime = s;
}
break;
case 2:
{
strftime(s, 32, "%H:%M : %S", p);
strTime = s;
}
break;
default:
break;
}
return strTime;
}