在c++中自定义时区格式化日期/时间

Formatting date/time in custom timezone in C++

本文关键字:日期 时间 格式化 时区 c++ 自定义      更新时间:2023-10-16

我需要创建一个自定义时区(纽约+ 7小时与美国夏时制设置)并使用此解析/格式化日期。

在Java中,我通常会这样做:

TimeZone tz = TimeZone.getTimeZone("America/New_York"); // Get new york tz
tz.setRawOffset(tz.getRawOffset() + 7 * 3600 * 1000); // add 7 hrs
DateFormat nyp7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
nyp7.setTimeZone(tz);
DateFormat utc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
utc.setTimeZone(TimeZone.getTimeZone("UTC"));
// US DST not in effect, NY is UTC-5, NY+7 is UTC+2
// below result is "2013-03-01 14:34:55"
nyp7.format(utc.parse("2013-03-01 12:34:55")); 
// US DST in effect, NY is UTC-4, NY+7 is UTC+3
// below result is "2013-04-01 15:34:55"
nyp7.format(utc.parse("2013-04-01 12:34:55")); 

如何在c++中做等效?我一直在挖掘boost日期时间库,但我迷路了。

通过创建自定义时区找到解决方案:

using namespace boost;
using namespace local_time;
using namespace gregorian;
using posix_time::time_duration;
using posix_time::ptime;
// Create a new timezone names
time_zone_names tzn("New York Plus 7 Time", "NYP7",
                    "New York Plus 7 Daylight Time", "NYP7D");
// With base UTC offset +2
int base_utc_offset_hr = 2;
time_duration utc_offset(base_utc_offset_hr,0,0);
// DST offset is +1 and starts and ends at 9am (2am + 7)
local_time::dst_adjustment_offsets adj_offsets(time_duration(1,0,0),
                                               time_duration(9,0,0),
                                               time_duration(9,0,0));
// DST starts the second Sunday of March and ends last Sunday of Nov
nth_kday_of_month start_rule(nth_kday_of_month::second, Sunday, Mar);
last_day_of_the_week_in_month end_rule(Sunday, Nov);
shared_ptr<dst_calc_rule> nyp7_rules(new nth_last_dst_rule(start_rule, end_rule));
// Construct the custom timezone
time_zone_ptr nyp7(new custom_time_zone(tzn, utc_offset, adj_offsets, nyp7_rules));

这可以用来检测DST是否有效,并将其偏移到源时间

// Determine whether or not dst in effect for time 't'
ptime dst_start = nyp7->dst_local_start_time(year);
ptime dst_end = nyp7->dst_local_end_time(year);
bool dst_on = dst_start <= t && t < dst_end;

然后可以根据boost的用户手册进行解析和格式化:http://www.boost.org/doc/libs/1_51_0/doc/html/date_time/date_time_io.html