D
D
Dmitry2012-11-07 13:33:52
C++ / C#
Dmitry, 2012-11-07 13:33:52

How to convert unix time to std::string?

Main goal: convert UNIX time to std::string
When I tried to use code like this:

std::string unixtimeToString( time_t ts )
{
    // _CRT_SECURE_NO_WARNINGS
    enum  { numCStringSize = 0x80 };
    const char strTimestampFmt[] = "%a, %Y-%b-%d, %H:%M:%S";

    char timeCStr[ numCStringSize ];

    std::tm * tmInfo = gmtime( &ts );

    std::strftime( &timeCStr[0], numCStringSize, strTimestampFmt, tmInfo );

    return std::string( timeCStr );
}

That received a fair warning from the MS Visual Studio 2008 compiler with code 4996.
Therefore, I rewrote it to a safer one:
std::string  unixtimeToString( uint32_t timeStamp )
{
    using namespace boost::posix_time;
    using namespace boost::gregorian;

    ptime unixEpoche( date( 1970, Jan, 1 ) );
    ptime ts(  unixEpoche + time_duration( 0, 0, timeStamp ) );

    return to_simple_string( ts );
}

But with this code, my tool that works on a large number of files (folder c:\windows\ on Win 7 x64 sp1) started to slow down.
Now I have three options:
1) Suppress warning message 4996 #pragma warning(push) -> #pragma warning(disable:4996) -> my code -> #pragma warning(pop)
2) Suppress at the project level by using project options _CRT_SECURE_NO_WARNINGS
3) The same as item 1, but put the disable / enable in external includes like disable_warning \ restore_warning and this will also make it possible to disable warnings in a portable way.
I don't like the first two. In the case of item 2, I have to agree that the compiler will not notify me at all about possible bugs. In the case of item 1, the readability of the code falls, even if not by much, but still somehow I don’t want to.
In view of the fact that the porridge in my head I want to ask others who did what?
PS:
Don't hit hard ;)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bogolt, 2012-11-07
@EvilsInterrupt

In my opinion, the most reasonable thing is to move the function code to a separate file, and wrap it with pragma push / pop with the annoying warning disabled.
As for the slowness of your program using boost conversion - this is a little strange, because if you access each file and then convert the time, then it is obvious that accessing the file system should be the bottleneck.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question