boost:从当前时区获取当前local_date_time

Ale*_*k86 10 c++ timezone boost boost-date-time

问题是:

  • 我知道如何让当地时间得到提升

代码:

    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;
Run Code Online (Sandbox Code Playgroud)
  • 我知道如何从机器获取当前时区数据(我希望它是正确的方式)

代码:

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"
Run Code Online (Sandbox Code Playgroud)

但是我仍然无法使用当前的time_zone获取local_date_time ...有人知道,怎么做?

Ale*_*k86 2

好吧,目前我还不知道完整的答案

但有代码可以帮助打印当前时区偏移量

(基于此处相关问题的答案(stackoverflow)和一些内部增强代码)

我绝对不确定它是否能在所有机器上正常工作,但现在总比没有好:

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 
}
Run Code Online (Sandbox Code Playgroud)