c++时间戳到人类可读的日期时间函数

标签 c++ timestamp

我有一个简单的函数,我需要从时间戳返回人类可读的日期时间,但不知何故 它以秒为单位返回相同的时间戳:

输入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/

相关文章:

c++ - LeakSanitizer : get run time leak reports?

c++ - 在 C++ 中创建一个文件,就像按右键->新建->新建文本文档一样

C++:为智能指针的字段隐式保留右值引用

php - 如何计算 MySQL 时间戳与 PHP 中当前时间之间的差异

c++ - 教 child C++ 时使用 "include stdafx.h"?

c++ - Linux 到 Windows C++ 端口

Java、Oracle db - trunc(nvl) 从日期时间对象中删除时间戳后出现时区问题

git - 是否可以(在 git 中)保留上次更改文件时的信息?

linux - FFMPEG rtsp流向输出文件添加时间戳

mongodb - Mongodb 从现有日期字段添加时间戳字段