time_t的字符串表示?

g33*_*z0r 29 c++ timestamp

time_t seconds;
time(&seconds);

cout << seconds << endl;
Run Code Online (Sandbox Code Playgroud)

这给了我一个时间戳.如何将该纪元日期变为字符串?

std::string s = seconds;
Run Code Online (Sandbox Code Playgroud)

不起作用

Fre*_*son 37

试试std::stringstream.

#include <string>
#include <sstream>

std::stringstream ss;
ss << seconds;
std::string ts = ss.str();
Run Code Online (Sandbox Code Playgroud)

围绕上述技术的一个很好的包装是Boost lexical_cast:

#include <boost/lexical_cast.hpp>
#include <string>

std::string ts = boost::lexical_cast<std::string>(seconds);
Run Code Online (Sandbox Code Playgroud)

对于这样的问题,我喜欢用Herb Sutter 链接The Manor Formatters of Manor Farm.

更新:

使用C++ 11,使用to_string().


小智 28

如果您想将时间放在可读的字符串中,请尝试此操作:

#include <ctime>

std::time_t now = std::time(NULL);
std::tm * ptm = std::localtime(&now);
char buffer[32];
// Format: Mo, 15.06.2009 20:20:00
std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm);  
Run Code Online (Sandbox Code Playgroud)

有关strftime()的进一步参考,请查看cppreference.com


小智 5

这里的最佳答案对我不起作用。

请参阅以下示例,演示建议的 stringstream 和 lexical_cast 答案:

#include <iostream>
#include <sstream>

int main(int argc, char** argv){
 const char *time_details = "2017-01-27 06:35:12";
  struct tm tm;
  strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
  time_t t = mktime(&tm); 
  std::stringstream stream;
  stream << t;
  std::cout << t << "/" << stream.str() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:1485498912/1485498912在这里找到


#include <boost/lexical_cast.hpp>
#include <string>

int main(){
    const char *time_details = "2017-01-27 06:35:12";
    struct tm tm;
    strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
    time_t t = mktime(&tm); 
    std::string ts = boost::lexical_cast<std::string>(t);
    std::cout << t << "/" << ts << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:1485498912/1485498912 找到:这里


评价第二高的解决方案在本地运行:

#include <iostream>
#include <string>
#include <ctime>

int main(){
  const char *time_details = "2017-01-27 06:35:12";
  struct tm tm;
  strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
  time_t t = mktime(&tm); 

  std::tm * ptm = std::localtime(&t);
  char buffer[32];
  std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", ptm);
  std::cout << t << "/" << buffer;
}
Run Code Online (Sandbox Code Playgroud)

输出:1485498912/2017-01-27 06:35:12 找到:这里