2016-12-27 44 views
1

我使用的检索使用boost::posix_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时间(并根据方面进行格式化),同时考虑到夏令时选项?

+1

夏令时间目前并未生效。您可能需要解决不同的问题。 –

回答

2

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

谢谢,它似乎工作。我将不得不研究我不该相信系统提供的默认时区的原因...... – Jepessen

+0

@Jepessen我认为如果服务器在您的控制之下通常很好。这只是针对某些时间点具有安全隐患的应用程序 – sehe