Simplest way to get current time in current timezone using boost::date_time?

风格不统一 提交于 2019-11-30 02:51:47

问题


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 printed.

What's the simplest way to obtain the same thing with boost::date_time ?

If I do this:

std::ostringstream msg;

boost::local_time::local_date_time t = 
  boost::local_time::local_sec_clock::local_time(
    boost::local_time::time_zone_ptr()
  );

boost::local_time::local_time_facet* lf(
  new boost::local_time::local_time_facet("%H-%M-%S")
);

msg.imbue(std::locale(msg.getloc(),lf));
msg << t;

Then msg.str() is an hour earlier than the time I want to see. I'm not sure whether this is because it's showing UTC or local timezone time without a DST correction (I'm in the UK).

What's the simplest way to modify the above to yield the DST corrected local timezone time ? I have an idea it involves boost::date_time:: c_local_adjustor but can't figure it out from the examples.


回答1:


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;



回答2:


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. :)



来源:https://stackoverflow.com/questions/2612938/simplest-way-to-get-current-time-in-current-timezone-using-boostdate-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!