44
time_t seconds;
time(&seconds);

cout << seconds << endl;

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

std::string s = seconds;

does not work

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 10
    It is obscene how difficult and time consuming the solutions are. Instead of a simple function returning `std::string` and taking `time_t` and `string`for parameters, with the second being format definition, there are solutions taking more than half a dozen lines of code. Isn't this grand? – ajeh Mar 29 '18 at 21:26
  • 1
    @ajeh: C++ is the Lego, not the Lego spaceship. ;) – Lightness Races in Orbit Feb 18 '19 at 23:56

9 Answers9

49

Try std::stringstream.

#include <string>
#include <sstream>

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

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

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

std::string ts = boost::lexical_cast<std::string>(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().

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
43

Try this if you want to have the time in a readable string:

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

For further reference of strftime() check out cppreference.com

nulldevice
  • 494
  • 3
  • 4
  • nulldevice, I wasn't clear above, but I wanted a string representation of the epoch date (timestamp). –  Jun 15 '09 at 18:25
5

The top answer here does not work for me.

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

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

Output: 1485498912/1485498912 Found here


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

Output: 1485498912/1485498912 Found: here


The 2nd highest rated solution works locally:

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

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


Mo Morsi
  • 111
  • 1
  • 3
1

Here's my formatter -- comments welcome. This q seemed like it had the most help getting me to my a so posting for anyone else who may be looking for the same.

#include <iostream>
#include "Parser.h"
#include <string>
#include <memory>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <thread>

using namespace std;
string to_yyyyMMddHHmmssffffff();

string to_yyyyMMddHHmmssffffff() {
    using namespace std::chrono;
    high_resolution_clock::time_point pointInTime = high_resolution_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(pointInTime);
    microseconds micros = duration_cast<microseconds>(pointInTime.time_since_epoch());
    std::size_t fractional_microseconds = micros.count() % 1'000'000;

    std:stringstream microstream;
    microstream << "00000" << fractional_microseconds;
    string formatted = microstream.str();
    int index = formatted.length() - 6;
    formatted = formatted.substr(index);
    std::stringstream dateStream;
    dateStream << std::put_time(std::localtime(&now_c), "%F %T") << "." << formatted;
    formatted = dateStream.str();

    return formatted;
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
No Refunds No Returns
  • 8,092
  • 4
  • 32
  • 43
  • Possibly not the best function name, and your code could do with some documenting comments ... but otherwise this isn't terrible ;) – Lightness Races in Orbit Feb 18 '19 at 23:58
  • 2
    I'd probably do a lot of things differently if do-overs were a real thing. All I can really say is appreciate my .net's .ToString("yyyy-MM-dd HH:mm:ss.fffffff") method more today than I did yesterday. – No Refunds No Returns Feb 20 '19 at 01:52
1

Standard C++ does not have any time/date functions of its own - you need to use the C localtime and related functions.

  • 7
    Your original question asked how to get a date, but it turns out that what you really wanted was the number of seconds as a string. It helps to be precise. –  Jun 15 '09 at 18:27
1

the function "ctime()" will convert a time to a string. If you want to control the way its printed, use "strftime". However, strftime() takes an argument of "struct tm". Use "localtime()" to convert the time_t 32 bit integer to a struct tm.

Matthias Wandel
  • 6,383
  • 10
  • 33
  • 31
1

The C++ way is to use stringstream.

The C way is to use snprintf() to format the number:

 char buf[16];
 snprintf(buf, 16, "%lu", time(NULL));
Reed Hedges
  • 1,590
  • 2
  • 15
  • 17
  • 2
    time_t isn't necessarily unsigned or of the same size as a long. In fact, it is usually signed: http://stackoverflow.com/questions/471248/what-is-ultimately-a-time-t-typedef-to – nitzanms Mar 20 '17 at 16:03
0

localtime did not work for me. I used localtime_s:

struct tm buf;
char dateString[26];
time_t time = time(nullptr);
localtime_s(&buf, &time);
asctime_s(dateString, 26, &buf);
0

There are a myriad of ways in which you might want to format time (depending on the time zone, how you want to display it, etc.), so you can't simply implicitly convert a time_t to a string.

The C way is to use ctime or to use strftime plus either localtime or gmtime.

If you want a more C++-like way of performing the conversion, you can investigate the Boost.DateTime library.

Josh Kelley
  • 56,064
  • 19
  • 146
  • 246