【问题标题】:boost::posix_time: retrieve time with daylight saving timeboost::posix_time: 使用夏令时检索时间
【发布时间】:2017-05-12 05:11:36
【问题描述】:

我正在使用以下方法使用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。在我的电脑(Windows 10)中,有一个选项自动调整夏令时

考虑到夏令时选项,有没有办法检索 PC 时间(并根据方面对其进行格式化)?

【问题讨论】:

  • 夏令时目前无效。您可能有不同的问题需要解决。

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


【解决方案1】:

我同意。 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();
}

【讨论】:

  • 谢谢,它似乎工作。我将不得不研究我不应该相信系统提供的默认时区的原因......
  • @Jepessen 我认为如果服务器在您的控制之下通常没问题。仅适用于某些时间点具有安全隐患的应用程序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2012-04-12
  • 2011-10-29
  • 2014-04-25
  • 2011-10-22
  • 2012-12-18
相关资源
最近更新 更多