c++ - boost::posix_time:检索带夏令时的时间

标签 c++ boost dst boost-date-time

我使用以下方法通过 boost::posix_time 检索包含当前时间的字符串:

wstring TimeField::getActualTime() const {
  // Defined elsewhere
  auto m_facet = new new boost::posix_time::wtime_facet(L"%Y%m%d-%H:%M:%f");
  std::locale m_locale(std::wcout.getloc(), m_facet);
  // method body
  std::basic_stringstream<wchar_t> wss;
  wss.imbue(m_locale);
  boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
  wss << now;
  return wss.str();
}

我得到以下结果:

20161227-22:52:238902

而在我的电脑上时间是 23:52。在我的 PC (windows 10) 中,自动调整夏令时选项已激活。

有没有办法在考虑夏令时选项的情况下检索 PC 时间(并根据方面格式化它)?

最佳答案

我同意。 DST 未生效。此外,根据定义,posix_time::ptime 不是时区感知时间戳(因此:POSIX 时间)。

但是,您当然可以要求本地时间而不是世界时间:

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

文档会警告您不要相信系统提供的默认时区信息和数据库,但您可能没问题。

Live On Coliru

#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <string>
#include <iostream>

namespace /*static*/ {
    // Defined elsewhere
    auto m_facet = new boost::posix_time::wtime_facet(L"%Y%m%d-%H:%M:%f");
    std::locale m_locale(std::wcout.getloc(), m_facet);
}

std::wstring getActualTime() {
    std::basic_stringstream<wchar_t> wss;
    wss.imbue(m_locale);

    wss << boost::posix_timemicrosec_clock::local_time();
    return wss.str();
}

int main() {
    std::wcout << getActualTime();
}

关于c++ - boost::posix_time:检索带夏令时的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353233/

相关文章:

c++ - 如何为包含映射的结构编写比较运算符?

c++ - Boost Beast WebSockets 每次读取时具有几次不确定的写入

java - 在夏令时前后将 Duration.ofDays(1) 和 Period.ofDays(1) 添加到 ZonedDateTime 之间的区别

Java ZonedDateTime 和英国夏令时间

c++ - 如何使用 boost 正态分布类?

javascript - 在 Javascript 中转换时区时如何考虑夏令时?

c++ - 来自具有相同图像的相机的 OpenCV 匹配图像不会产生 100% 匹配

c++ - 在 CLion 中编译时出现问题

c++ - 在以下程序中使用 C++ 获取 SIGABRT

c++ - 关于shared_ptr、scoped_ptr和shared_array的一些问题