1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <string>
#include <ctime>
static constexpr const char* time_fmt = "%Y%m%d%H%M%S" ; // eg. 20180302022715
std::string timestamp( std::time_t t = std::time(nullptr) )
{
char buffer[64] {} ;
std::strftime( buffer, sizeof(buffer), time_fmt, std::localtime( std::addressof(t) ) ) ;
return buffer ;
}
std::time_t to_time_t( const std::string& timestamp ) // throws on bad timestamp
{
std::tm tm {} ;
tm.tm_year = std::stoi( timestamp.substr(0,4) ) - 1900 ;
tm.tm_mon = std::stoi( timestamp.substr(4,2) ) - 1 ;
tm.tm_mday = std::stoi( timestamp.substr(6,2) ) ;
tm.tm_hour = std::stoi( timestamp.substr(8,2) ) ;
tm.tm_min = std::stoi( timestamp.substr(10,2) ) ;
tm.tm_sec = std::stoi( timestamp.substr(12,2) ) ;
return std::mktime( std::addressof(tm) ) ;
}
double days_from( const std::string& timestamp_begin, const std::string& timestamp_end )
{
static constexpr int SECS_PER_DAY = 24 * 60 * 60 ;
return std::difftime( to_time_t(timestamp_end), to_time_t(timestamp_begin) ) / SECS_PER_DAY ;
}
int main()
{
const auto str = timestamp() ;
std::cout << str << '\n' // eg. 20180302022715
<< std::boolalpha << ( str == timestamp( to_time_t(str) ) ) << '\n' // true
<< days_from( str, timestamp( to_time_t(str) + 36*60*60 ) ) << '\n' // 1.5 if it's unix time
<< days_from( str, timestamp( to_time_t(str) - 60*60*60 ) ) << '\n' ; // -2.5 if it's unix time
}
|