String representation of time_t?

前端 未结 9 785
悲&欢浪女
悲&欢浪女 2020-12-09 02:05
time_t seconds;
time(&seconds);

cout << seconds << endl;

This gives me a timestamp. How can I get that epoch date into a string?<

9条回答
  •  暖寄归人
    2020-12-09 02:21

    Try std::stringstream.

    #include 
    #include 
    
    std::stringstream ss;
    ss << seconds;
    std::string ts = ss.str();
    

    A nice wrapper around the above technique is Boost's lexical_cast:

    #include 
    #include 
    
    std::string ts = boost::lexical_cast(seconds);
    

    And for questions like this, I'm fond of linking The String Formatters of Manor Farm by Herb Sutter.

    UPDATE:

    With C++11, use to_string().

提交回复
热议问题