在c++中自定义时区格式化日期/时间
Formatting date/time in custom timezone in C++
我需要创建一个自定义时区(纽约+ 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
相关文章:
- 使用 C++将时间戳转换为格式化的日期时间
- C++代码的 C# 日期时间等效项是什么?
- 如何在提升日期时间中创建日期范围?
- 在 c++ 中将 ISO 日期时间转换为本地日期时间并提取时间
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 如何将毫秒的日期时间字符串转换为 UNIX 时间戳
- 扩展中的日期时间对象方法C++问题
- 将DateTime字符串分为C 的日期时间
- C++以微秒为单位解析日期/时间
- 仅将纪元字符串保存到 mysql 日期时间年/月/日,但没有小时分钟秒
- 使用提升解析日期时间字符串:采用个位数小时格式
- C++ Poco SQL 查询不返回具有'between'和'and'日期时间绑定的结果
- 快速将带有时区的日期时间字符串转换为 UNIX 时间戳(C++)
- 从C 的时间戳提取日期时间戳
- 标准::get_time 中的日期时间格式
- 生成包含分数和时区的完整 iso 日期时间表示字符串
- 通过 ODBC C++将带有日期时间的记录插入 SQL Server 2014 的问题
- 在 C++20 中获取当前日期/时间是否线程安全?
- mongocxx:插入日期时间
- Poco 日期时间格式化程序 - 使用当前时区打印时间戳