输入:带有日期和可选时间的字符串。不同的表示会很好但很有必要。字符串是用户提供的,可能格式不正确。例子:
"2004-03-21 12:45:33"
(我认为这是默认布局)“2004/03/21 12:45:33”
(可选布局)"23.09.2004 04:12:21"
(德语格式,可选)“2003-02-11”
(时间可能会丢失)
需要的输出:自纪元 (1970/01/01 00:00:00) 或其他某个固定点以来的秒数。
奖励:另外,读取本地系统时间的 UTC 偏移量会很棒。
假设输入是相关机器上的本地时间。 输出必须是 UTC。系统只有 Linux(需要 Debian Lenny 和 Ubuntu)。
我曾尝试使用 boost/date_time
,但必须承认我无法完全理解文档。以下工作无需从系统本地时间转换为 UTC:
std::string date = "2000-01-01";
boost::posix_time::ptime ptimedate = boost::posix_time::time_from_string(date);
ptimedate += boost::posix_time::hours(Hardcoded_UTC_Offset);// where to get from?
struct tm = boost::posix_time::to_tm(ptimedate);
int64_t ticks = mktime(&mTmTime);
我认为 boost::date_time
可以提供所需的 UTC 偏移量,但我不知道如何。
最佳答案
虽然我不知道如何在boost中格式化一位数的月份输入,但我可以在两位数编辑后做到:
#include <iostream>
#include <boost/date_time.hpp>
namespace bt = boost::posix_time;
const std::locale formats[] = {
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))};
const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
std::time_t pt_to_time_t(const bt::ptime& pt)
{
bt::ptime timet_start(boost::gregorian::date(1970,1,1));
bt::time_duration diff = pt - timet_start;
return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
}
void seconds_from_epoch(const std::string& s)
{
bt::ptime pt;
for(size_t i=0; i<formats_n; ++i)
{
std::istringstream is(s);
is.imbue(formats[i]);
is >> pt;
if(pt != bt::ptime()) break;
}
std::cout << " ptime is " << pt << '\n';
std::cout << " seconds from epoch are " << pt_to_time_t(pt) << '\n';
}
int main()
{
seconds_from_epoch("2004-03-21 12:45:33");
seconds_from_epoch("2004/03/21 12:45:33");
seconds_from_epoch("23.09.2004 04:12:21");
seconds_from_epoch("2003-02-11");
}
请注意,从纪元开始的秒数输出将假定日期为 UTC:
~ $ ./test | head -2
ptime is 2004-Mar-21 12:45:33
seconds from epoch are 1079873133
~ $ date -d @1079873133
Sun Mar 21 07:45:33 EST 2004
您可能会使用 boost::posix_time::c_time::localtime()
来自 #include <boost/date_time/c_time.hpp>
假设输入在当前时区中完成此转换,但它相当不一致:例如,对我来说,在夏令时结束时,今天和下个月之间的结果会有所不同。
关于c++ - 如何从字符串中解析日期/时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3786201/