c++ - 使用 boost/std 库解析带时区的日期

标签 c++ datetime boost std

我想将输入日期字符串(输入中未提供时间)(如“2017-05-04”)转换为 unix 时间戳,时间为“00:00:01”,时区为太平洋时间(“美国/洛杉矶)。

我不太确定如何执行此操作 - 我使用 boost::posix_time::time_from_string 进行了探索,但它似乎无法处理时区。 任何建议将不胜感激!

最佳答案

使用 Howard Hinnant's free, open source, C++11/14/17 timezone library ,您可以使用以下语法执行此操作:

#include "tz.h"
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>

date::sys_seconds
my_parse(const std::string& in)
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    local_seconds ls;
    istringstream infile{in};
    infile >> parse("%F", ls);
    assert(!infile.fail());
    return make_zoned("America/Los_Angeles", ls + seconds{1}).get_sys_time();
}

int
main()
{
    std::cout << my_parse("2017-05-04").time_since_epoch().count() << '\n';
}

这个程序输出:

1493881201

使用类似 http://www.convert-unix-time.com/?t=1493881201 的网站您可以确认 1493881201 对应于世界标准时间 2017 年 5 月 4 日星期四 07:00:01 AM,即 PDT 2017 年 5 月 4 日星期四 00:00:01 AM。

关于c++ - 使用 boost/std 库解析带时区的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927760/

相关文章:

sql - PostgreSQL 获取两个日期时间/时间戳之间的随机日期时间/时间戳

c++ - 在 Visual Studio 2008 中使用 Boost 时出错

c++ - 在 Boost MPL 和 Fusion 中启用任意大小的集合

c++ - 为什么 boost::serialization 不检查 XML 文件中的标签名称?

c++ - Gmock 只期待一个特定的调用

C++ 正则表达式

python - 将时间戳舍入到微秒 - pandas

java - FastDateFormat解析问题

c++ - 函数参数的...是什么?

c++ - CUDA 探查器 : Calculate memory and compute utilization