Search code examples
c++boostdstboost-date-time

boost::posix_time: retrieve time with daylight saving time


I'm using the following method for retrieving a string containing the current time using 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();
}

I obtain following result:

20161227-22:52:238902

while in my pc time is 23:52. In my PC (windows 10) there's the option Adjust for daylight saving time automatically activated.

Is there a way to retrieve the PC time (and format it according to facet) taking into account also the daylight saving time option?


Solution

  • I agree. DST is not in effect. Also, posix_time::ptime by very definition is not a timezone-aware timestamp (hence: POSIX time).

    However, instead of universal time, you could of course ask for a local-time:

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

    The docs will warn you not to trust system-supplied default timezone info and databases, but you'll probably be fine.

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