String representation of time_t?

前端 未结 9 795
悲&欢浪女
悲&欢浪女 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:36

    The top answer here does not work for me.

    See the following examples demonstrating both the stringstream and lexical_cast answers as suggested:

    #include 
    #include 
    
    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;
    }
    

    Output: 1485498912/1485498912 Found here


    #include 
    #include 
    
    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(t);
        std::cout << t << "/" << ts << std::endl;
        return 0;
    }
    

    Output: 1485498912/1485498912 Found: here


    The 2nd highest rated solution works locally:

    #include 
    #include 
    #include 
    
    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;
    }
    

    Output: 1485498912/2017-01-27 06:35:12 Found: here


提交回复
热议问题