C++ 時間戳轉本地時間 函式
阿新 • • 發佈:2019-02-18
時間戳轉本地時間在網上找了一上午,中午研究出來一個,同時進行了一些改進。
.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;
}