c ++时间戳到人类可读的日期时间函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14436462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ time stamp to human readable datetime function
提问by user63898
i have simple function that i need to return human readable date time from timestamp but somehow it returns the same timestam in seconds:
我有一个简单的函数,我需要从时间戳返回人类可读的日期时间,但不知何故它以秒为单位返回相同的时间戳:
input 1356953890
输入 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;
}
output 1231133812
输出 1231133812
this is how i call it :
我是这样称呼它的:
long timestamp = 1356953890L ;
std::string hreadble = UT::timeStampToHReadble(timestamp);
std::cout << hreadble << std::endl;
and the output is : 1231133812 and i what it to be somekind of this format : 31/1/ 2012 11:38:10 what im missing here ?
输出是:1231133812,我是什么这种格式:31/1/2012 11:38:10 我在这里缺少什么?
UTDATE :
the solution
strftime(timestr, sizeof(timestr), " %H:%M:%S %d/%m/%Y", dt);
UTDATE :
解决方案 strftime(timestr, sizeof(timestr), " %H:%M:%S %d/%m/%Y", dt);
回答by ormurin
It can be boiled down to:
可以归结为:
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);
}
Changes:
变化:
- I would prefer to do the casting outside the function. It would be weird to cast a time_t to a long before calling the function, if the caller had the time_t data.
- It's not necessary to have two buffers (and therefore not necessary to copy with sprintf)
- 我更愿意在函数之外进行转换。如果调用者有 time_t 数据,在调用函数之前将 time_t 强制转换为 long 会很奇怪。
- 没有必要有两个缓冲区(因此没有必要用 sprintf 复制)