我有一个简单的函数,我需要从时间戳返回人类可读的日期时间,但不知何故 它以秒为单位返回相同的时间戳:
输入1356953890
std::string UT::timeStampToHReadble(long timestamp)
{
const time_t rawtime = (const time_t)timestamp;
struct tm * dt;
char timestr[30];
char buffer [30];
dt = localtime(&rawtime);
// use any strftime format spec here
strftime(timestr, sizeof(timestr), "%m%d%H%M%y", dt);
sprintf(buffer,"%s", timestr);
std::string stdBuffer(buffer);
return stdBuffer;
}
输出1231133812
我是这样调用它的:
long timestamp = 1356953890L ;
std::string hreadble = UT::timeStampToHReadble(timestamp);
std::cout << hreadble << std::endl;
输出为:1231133812 我什么是这种格式: 31/1/2012 11:38:10 我在这里缺少什么?
UTDATE :
解决方案
strftime(timestr, sizeof(timestr), "%H:%M:%S %d/%m/%Y", dt);
最佳答案
可以归结为:
std::string UT::timeStampToHReadble(const time_t rawtime)
{
struct tm * dt;
char buffer [30];
dt = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%m%d%H%M%y", dt);
return std::string(buffer);
}
变化:
- 我更愿意在函数外进行转换。如果调用者有 time_t 数据,那么在调用函数之前将 time_t 转换为 long 会很奇怪。
- 没有必要有两个缓冲区(因此没有必要用 sprintf 复制)
关于c++时间戳到人类可读的日期时间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14436462/