【发布时间】:2016-08-11 13:21:42
【问题描述】:
在我的一个程序中,我必须多次阅读几种不同的格式。然而,在所有格式中,时间都以 UTC 给出(即不在我当地的时区)。对于接受日期字符串和格式字符串并输出std::time_t 时间戳的函数来说,最好的方法是什么?
目前我正在使用 boost
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
std::time_t to_timestamp_utc(const std::string& _dateString) {
using namespace boost::gregorian;
using namespace boost::posix_time;
return to_time_t(ptime(from_undelimited_string(_dateString)));
}
但这仅适用于“YYYYMMDD”格式。另一方面,标准库函数std::get_time 假定输入日期在我的本地时间而不是UTC 格式(或者至少我还没有找到改变它的方法)。欢迎提出任何建议。
当前解决方案基于 Maxim Egorushkin 的建议。
std::time_t utc_to_timestamp(const std::string& _dateString, const std::string& _format) {
// Set sec, min, hour to zero in case the format does not provide those
std::tm timeStruct;
timeStruct.tm_sec = 0;
timeStruct.tm_min = 0;
timeStruct.tm_hour = 0;
char* const result = strptime(_dateString.c_str(), _format.c_str(), &timeStruct);
// Throw exception if format did not work
REQUIRE(result == _dateString.c_str()+_dateString.size(), "Failed to parse dateTime.");
return timegm(&timeStruct);
}
【问题讨论】:
-
您需要哪些格式? (英国、美国、?)
-
您需要知道您期望的格式。例如。
07-06-2016是模棱两可的,因为在美国他们做 mm-dd-yyyy,而在欧盟他们做 dd-mm-yyyy。 -
@BiagioFesta 我主要需要
yyyy-mm-dd hh:mm:ss、yyyymmdd和dd.mm.yyyy hh:mm,但最好让函数像std::get_time那样采用任意格式作为参数。 -
@MaximEgorushkin 我确实事先知道它们,我只是希望能够将格式作为附加参数,因为我需要几种格式(请参阅前面的评论)。
-
如果日期最初是从流中读取的,您可以使用
std::ge_time将其解析为tm。