gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:21:48 24 4
gpt4 key购买 nike

问题是:

  • 我知道如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com