Thanks to people who contributed to this question.
I did a bit of hack to it to convert a string to epoch time with a flexible custom format.
I do not understand why my format "%m/%d/%Y %H:%M:%S"
fails but the other one %Y/%m/%d %H:%M:%S
works. How should I fix it?
#include <iostream>
#include <boost/date_time.hpp>
namespace bt = boost::posix_time;
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,const std::string format_string)
{
const std::locale format = std::locale(std::locale::classic(),new bt::time_input_facet(format_string));
bt::ptime pt;
std::istringstream is(s);
is.imbue(format);
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("7/23/2012 4:10:43","%m/%d/%Y %H:%M:%S");
seconds_from_epoch("2004/03/21 12:45:33","%Y/%m/%d %H:%M:%S");
}
Results:
g++ main.cpp -Wall -Wconversion -Wfatal-errors -Wextra -std=c++11 -o main
./main
ptime is not-a-date-time
seconds from epoch are 9223372036854
ptime is 2004-Mar-21 12:45:33
seconds from epoch are 1079873133