tags:

views:

446

answers:

1

In C++ what is the simplest way to add one day to a date in this format:

"20090629-05:57:43"

Probably using Boost 1.36 - Boost::date, Boost::posix_date or any other boost or std library functionality, I'm not interested in other libraries.

So far I came up with:

  • format the string (split date and time parts as string op) to be able to initialize boost::gregorian::date, date expects format like:

    "2009-06-29 05:57:43"

    I have

    "20090629-05:57:43"

  • add one day (boost date_duration stuff)

  • convert back to_simple_string and append the time part (string operation)

Is there any easier/niftier way to do this?

I am looking at run time efficiency.

Example code for the above steps:

using namespace boost::gregorian;
string orig("20090629-05:57:43");
string dday(orig.substr(0,8));
string dtime(orig.substr(8));

date d(from_undelimited_string(dday));
date_duration dd(1);
d += dd;
string result(to_iso_string(d) + dtime);

result:

20090630-05:57:43
+1  A: 

That's pretty close to the simplest method I know of. About the only way to simplify it further would be using facets for the I/O stuff, to eliminate the need for string manipulation:

#include <iostream>
#include <sstream>
#include <locale>
#include <boost/date_time.hpp>

using namespace boost::local_time;

int main() {
 std::stringstream ss;
 local_time_facet* output_facet = new local_time_facet();
 local_time_input_facet* input_facet = new local_time_input_facet();
 ss.imbue(std::locale(std::locale::classic(), output_facet));
 ss.imbue(std::locale(ss.getloc(), input_facet));

 local_date_time ldt(not_a_date_time);

 input_facet->format("%Y%m%d-%H:%M:%S");
 ss.str("20090629-05:57:43");
 ss >> ldt;

 output_facet->format("%Y%m%d-%H:%M:%S");
 ss.str(std::string());
 ss << ldt;

 std::cout << ss.str() << std::endl;
}

That's longer, and arguably harder to understand, though. I haven't tried to prove it, but I suspect it would be about equal runtime-efficiency that way.

Head Geek
+1, interesting solution, I'll have a look. I assume that I could reuse facets with the format and then just pass the date through it.
stefanB
I don't see any reason you couldn't.One added point: since this uses local time, you might have an occasional problem with Daylight Savings Time changes. Easy enough to get around by setting the time zone to GMT, but it's something to consider.
Head Geek
in my specific case I'm dealing with GMT time
stefanB