因此,如果您还需要获得正确的 UTC 偏移量,那么应该稍微修改一下我之前的示例以生成正确的时区字符串:
static boost::posix_time::time_duration utc_offset(
second_clock::local_time() - second_clock::universal_time());
std::ostringstream ss_posix_tz_def;
// We don't care about real zone name so, just put any three letters.
ss_posix_tz_def << "LOC" << utc_offset;
string posix_tz_def = ss_posix_tz_def.str();
另一个解决方案是编写一个全新的时区提供程序。像这个简单的:
// We assume local TZ doesn't have DST, UTC offset is calculated basing on
// local system clocks. Thus, using of this provider for time calculations for
// an arbitrary date is not a good idea.
class machine_time_zone : public boost::local_time::custom_time_zone {
public:
typedef boost::local_time::custom_time_zone base_type;
typedef base_type::time_duration_type time_duration_type;
machine_time_zone()
: boost::local_time::custom_time_zone(
time_zone_names("Local machine TZ", "LOC", "", ""),
GetUTCOffset(),
boost::local_time::dst_adjustment_offsets(
time_duration_type(0, 0, 0),
time_duration_type(0, 0, 0), time_duration_type(0, 0, 0)),
boost::shared_ptr<boost::local_time::dst_calc_rule>()) {
}
// This method is not precise, real offset may be several seconds more or less.
static const boost::posix_time::time_duration& GetUTCOffset() {
using boost::posix_time::second_clock;
static boost::posix_time::time_duration utc_offset(
second_clock::local_time() - second_clock::universal_time());
return utc_offset;
}
};
只需在构造时传递它local_date_time
:
local_date_time ldt(second_clock::local_time(),
time_zone_ptr(new machine_time_zone()));