使用boost :: date_time在当前时区获取当前时间的最简单方法?

时间:2010-04-10 10:00:23

标签: c++ boost timezone debian boost-date-time

如果我在命令行(Debian / Lenny)上date +%H-%M-%S,我会得到一个用户友好的(不是UTC,而不是DST-less,正常人在他们的手表上的时间)打印时间。

使用boost::date_time获取相同内容的最简单方法是什么?

如果我这样做:

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;

然后msg.str()比我想要看到的时间早一个小时。我不确定这是因为它显示UTC或本地时区时间而没有DST校正(我在英国)。

修改上述内容以获得DST更正的本地时区时间的最简单方法是什么?我知道它涉及boost::date_time:: c_local_adjustor,但无法从示例中弄清楚。

3 个答案:

答案 0 :(得分:17)

这就是我想要的:

  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;

答案 1 :(得分:4)

虽然这不是使用boost :: date_time,但使用boost :: locale相对容易,因为它更适合这项任务。因为您只需要从当前区域设置获取格式化的时间。

当您处理甘特图/计划计算等软件时,应该使用恕我直言boost :: date_time,你有很多date_time算术吗?但仅仅是为了使用时间并对其进行一些算术运算,使用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;
}

现在应输出:15-45-48。 :)

答案 2 :(得分:0)

我还没有找到其他答案足够方便,因此下面的示例展示了如何在完全控制单位的情况下获取本地或世界时间:

#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();
}

注意:time_of_day结构没有.microseconds().nanoseconds()函数,只有.fractional_seconds()返回一个整数,该整数是与配置有关的单位的倍数。 .num_fractional_digits()可用于获取精度信息,其中10 ^ frac_digits是等于1秒的fractional_seconds数。

要获得独立于配置的亚秒级单位,可以使用total_ milli/micro/nano _seconds()函数作为模数来解决。

相关问题