Vì vậy, nếu bạn cũng cần phải được tính theo giờ UTC đúng bù đắp hơn ví dụ trước đây của tôi nên được sửa đổi một chút để tạo ra chuỗi múi giờ chính xác:
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();
Một giải pháp khác được viết toàn bộ một nhà cung cấp múi giờ mới. Như thế này đơn giản:
// 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;
}
};
Chỉ cần vượt qua nó khi xây dựng local_date_time
:
local_date_time ldt(second_clock::local_time(),
time_zone_ptr(new machine_time_zone()));
Bạn có * phải * để in thời gian trong localtime? Nếu bạn có thể sử dụng UTC bạn sẽ tiết kiệm cho mình tất cả các loại nhức đầu. –
Hãy xem [Hướng dẫn IO ngày giờ] (http://www.boost.org/doc/libs/1_48_0/doc/html/date_time/date_time_io.html#date_time.io_tutorial)? –
"Bạn có phải in giờ địa phương không?" Có, tôi phải: ( – Alek86