5

如何获取当前的 UTC 偏移量(如时区,但只是当前时刻的 UTC 偏移量)?

我需要像“+02:00”这样的答案。

4

2 回答 2

15

There are two parts to this question:

  1. Get the UTC offset as a boost::posix_time::time_duration
  2. Format the time_duration as specified

Apparently, getting the local time zone is not exposed very well in a widely implemented API. We can, however, get it by taking the difference of a moment relative to UTC and the same moment relative to the current time zone, like this:

boost::posix_time::time_duration get_utc_offset() {
    using namespace boost::posix_time;

    // boost::date_time::c_local_adjustor uses the C-API to adjust a
    // moment given in utc to the same moment in the local time zone.
    typedef boost::date_time::c_local_adjustor<ptime> local_adj;

    const ptime utc_now = second_clock::universal_time();
    const ptime now = local_adj::utc_to_local(utc_now);

    return now - utc_now;
}

Formatting the offset as specified is just a matter of imbuing the right time_facet:

std::string get_utc_offset_string() {
    std::stringstream out;

    using namespace boost::posix_time;
    time_facet* tf = new time_facet();
    tf->time_duration_format("%+%H:%M");
    out.imbue(std::locale(out.getloc(), tf));

    out << get_utc_offset();

    return out.str();
}

Now, get_utc_offset_string() will yield the desired result.

于 2010-10-04T10:54:03.423 回答
4

从 C++11 开始,您可以使用 chrono 和std::put_time

#include <chrono>
#include <iomanip>
#include <iostream>
int main ()
{

  using sc = std::chrono::system_clock;
  auto tm = sc::to_time_t(sc::now());

  std::cout << std::put_time(std::localtime(&tm), "formatted time: %Y-%m-%dT%X%z\n");

  std::cout << "just the offset: " << std::put_time(std::localtime(&tm), "%z\n");

}

这会产生以下输出:

格式化时间:2018-02-15T10:25:27+0100

只是偏移量:+0100

于 2018-02-15T09:26:59.660 回答