7

タイムスタンプから人間が読める日付時刻を返す必要がある単純な関数がありますが、どういうわけか同じタイムスタンプを秒単位で返します:

入力 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);

4

1 に答える 1

10

それは次のように要約できます。

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);
}

変更点:

  • 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)
于 2014-01-23T08:34:52.130 に答える