Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get local time with boost

Tags:

c++

time

boost

I didn't find this in documentation: how to get local time (better formatted) with boost?

like image 610
Max Frai Avatar asked Mar 22 '10 14:03

Max Frai


1 Answers

Use posix_time to construct a time object from the system clock.

For example, this would output the current system time as an ISO-format string:

namespace pt = boost::posix_time;
pt::to_iso_string(pt::second_clock::local_time());

For formatting alternatives, see the “Conversion to String” section of the above-linked reference and the Date Time Input/Output reference. Alternatively, you can build your own output string using the accessor functions. For example, to get a US-style date:

namespace pt = boost::posix_time;
pt::ptime now = pt::second_clock::local_time();
std::stringstream ss;
ss << static_cast<int>(now.date().month()) << "/" << now.date().day()
    << "/" << now.date().year();
std::cout << ss.str() << std::endl;

Note the month is cast to int so it will display as digits. The default output facet will display it as the three-letter month abbreviation (“Mar” for March).

like image 145
Nate Avatar answered Sep 21 '22 13:09

Nate