c++ - boost:从机器获取带有当前时区的当前 local_date_time

标签 c++ boost timezone boost-date-time

问题是:

  • 我知道如何在 boost 中获取本地时间

代码:

    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;
  • 我知道如何从机器获取当前时区数据(我希望这是正确的方法)

代码:

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"

但我仍然无法获得当前时区的 local_date_time...有人知道该怎么做吗?

最佳答案

好吧,至于现在我还不知道完整的答案

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

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

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

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 
}

关于c++ - boost:从机器获取带有当前时区的当前 local_date_time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8746848/

相关文章:

c++ - 数字在数组中出现的次数

c++ - 为什么 push_back() 会导致 malloc() 处理的数据崩溃?

c++ - 使用带有 Boost ASIO 的 UDP 的文件套接字 I/O

c# - TimeZoneInfo 成员的单元测试的测试结果不正确

timezone - ICS 时区不工作

MySQL CONVERT_TZ 不适用于 2 个相同的转换

c++ - 无符号类型的 Eigen 运算

c++ - 同一线程上的两个连续 memory_order_release 存储可以相互重新排序吗?

c++ - 使用 boost::interprocess::file_lock 创建一个锁定文件

c++ - 使用 boost::archive::binary_iarchive 的内存泄漏