Question

I want to format a date and time as a string using the format:

20130630-03:11:45.862

I can do most of this by using strftime, however there is no clear way to achieve fractional seconds on the end.

My current code is:

time_t rawtime;
time(&rawtime);
tm* timeinfo = localtime(&rawtime);
char buffer[80];
strftime(buffer, 80, "%G%m%d-%I:%M:%S", timeinfo);

This produces the value without the fractional seconds part.

However ultimately I just want to have a string version of the date in this format, and don't care what API it takes.

I'm using g++ on Linux in case it's relevant.

Was it helpful?

Solution

If you don't care about the API, you could use boost::date_time and it's time_facet.

Short example so far:

// setup facet and zone
// this facet should result like your desired format
std::string facet="%Y%m%d-%H:%M:%s";
std::string zone="UTC+00";

// create a facet
boost::local_time::local_time_facet *time_facet;
time_facet = new boost::local_time::local_time_facet;

// create a stream and imbue the facet
std::stringstream stream(std::stringstream::in | std::stringstream::out);
stream.imbue(std::locale(stream.getloc(), time_facet));

// create zone
boost::local_time::time_zone_ptr time_zone;
time_zone.reset(new boost::local_time::posix_time_zone(zone));

// write local from calculated zone in the given facet to stream
stream << boost::local_time::local_microsec_clock::local_time(time_zone);

// now you can get the string from stream
std::string my_time = stream.str();

This example is maybe incomplete, because I copied some code out of mine, but I hope you got the point.

With the facet, you can setup your format. The %s (small s with, big S without fractial) setup seconds with fractial. You can read this in the documentation facet format.

The timezone is for calculating your local machine time to the right zone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top