我想将输入日期字符串(输入中未提供时间)(如“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/