boost: get the current local_date_time with current time zone from the machine

Alek86 picture Alek86 · Jan 5, 2012 · Viewed 11.2k times · Source

The problems is:

  • I know how to get the local time in boost

the code:

    boost::local_time::local_date_time currentTime(
        boost::posix_time::second_clock::local_time(),
        boost::local_time::time_zone_ptr());
    std::cout << currentTime.local_time() << std::endl;
  • I know how to get the current time zone data from the machine (I hope it's a right way)

the code:

tzset();
// the var tzname will have time zone names
// the var timezone will have the current offset
// the var daylight should show me if there is daylight "on"

but still I can't get local_date_time with the current time_zone... Does someone know, how to do it?

Answer

Alek86 picture Alek86 · Jan 5, 2012

OK, as for now I still don't know the whole answer

but there is code, which could help to print the current time zone offset

(based on an answer for a related question here (stackoverflow) and some inner boost code)

I'm absolutely not sure it's will work correctly on all machines, but for now it's better than nothing:

boost::posix_time::time_duration getUtcOffset(const boost::posix_time::ptime& utcTime)
{
    using boost::posix_time::ptime;
    const ptime localTime = boost::date_time::c_local_adjustor<ptime>::utc_to_local(utcTime);
    return localTime - utcTime;
}

std::wstring getUtcOffsetString(const boost::posix_time::ptime& utcTime)
{
    const boost::posix_time::time_duration td = getUtcOffset(utcTime);
    const wchar_t fillChar = L'0';
    const wchar_t timeSeparator = L':';

    std::wostringstream out;
    out << (td.is_negative() ? L'-' : L'+');
    out << std::setw(2) << std::setfill(fillChar)
        << boost::date_time::absolute_value(td.hours());
    out << L':';
    out << std::setw(2) << std::setfill(fillChar)
        << boost::date_time::absolute_value(td.minutes());
    return out.str();
}
int main()
{
    const boost::posix_time::ptime utcNow =
        boost::posix_time::second_clock::universal_time();

    const std::wstring curTimeOffset = getUtcOffsetString(utcNow);
    std::wcout << curTimeOffset.c_str() << std::endl;  // prints  -05:00  on my comp 
}