If I do date +%H-%M-%S
on the commandline (Debian/Lenny), I get a user-friendly (not UTC, not DST-less, the time a normal person has on their wristwatch) time p
I haven't found other answers to be convenient enough, so here is an example that showcases how to get a local or universal time with full control of units:
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/format.hpp>
#include <iostream>
int main()
{
auto const now = boost::posix_time::microsec_clock::local_time(); // or universal_time() for GMT+0
if (now.is_special()) {
// some error happened
return 1;
}
// example timestamp (eg for logging)
auto const t = now.time_of_day();
boost::format formater("[%02d:%02d:%02d.%06d]");
formater % t.hours() % t.minutes() % t.seconds() % (t.total_microseconds() % 1000000);
std::cout << formater.str();
}
Note: the time_of_day
struct has no .microseconds()
or .nanoseconds()
functions, there is only .fractional_seconds()
which returns an integer that is a multiple of configuration-dependent unit. .num_fractional_digits()
can be used to obtain precision information where 10
^ frac_digits
is the number of fractional_seconds
that is equal to 1 second.
To obtain configuration-independent sub-second units one can perform modulo with the total_ milli/micro/nano _seconds()
functions as a workaround.
While this is not using boost::date_time it's relatively easy with boost::locale, which is quite more adapted for this task. As your need is simply getting a formatted time from the current locale.
IMHO boost::date_time should be used when you deal with softwares like gantt/planning computations, were you have alot of date_time arithmetic. But simply for using time and doing some arithmetic on it, you will faster success with boost::locale.
#include <iostream>
#include <boost/locale.hpp>
using namespace boost;
int main(int argc, char **argv) {
locale::generator gen;
std::locale::global(gen(""));
locale::date_time now;
std::cout.imbue(std::locale());
std::cout << locale::as::ftime("%H-%M-%S") << now << std::endl;
return 0;
}
Right now it should output : 15-45-48. :)
This does what I want:
namespace pt = boost::posix_time;
std::ostringstream msg;
const pt::ptime now = pt::second_clock::local_time();
pt::time_facet*const f = new pt::time_facet("%H-%M-%S");
msg.imbue(std::locale(msg.getloc(),f));
msg << now;