views:

40

answers:

1

How do I get the current UTC offset (as in time zone, but just the UTC offset of the current moment)?

I need an answer like "+02:00".

+3  A: 

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.

Magnus Hoff
It's a complicated issue; a specific UTC offset may correspond to multiple timezones, for example.
Roger Pate
@Roger: So... I guess the correct way to say it is that I am looking for the UTC offset for the current time, not the time zone?
Magnus Hoff
@Magnus: Yes, if that's what you're interested in (which is also what it sounds like to me), this answer is spot on. I was responding more to "getting the local time zone is not exposed very well in a widely implemented API." Just be aware that the UTC offset you get for today could be different later (or earlier).
Roger Pate
@Roger: I updated my question to be more precise. Of course, your comment still stands with regards to "getting the local time zone..." :)
Magnus Hoff