Created
January 8, 2013 15:58
-
-
Save icholy/4484920 to your computer and use it in GitHub Desktop.
time parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <sstream> | |
#include <cstdio> | |
#include <iostream> | |
#include <algorithm> | |
#include <stdexcept> | |
#include <vector> | |
#include <memory> | |
#include <chrono> | |
#include <thread> | |
namespace chr = std::chrono; | |
using std::string; | |
using std::vector; | |
std::time_t parse_start_time (string const& duration_str) | |
{ | |
try | |
{ | |
return std::stoi(duration_str); | |
} | |
catch (std::invalid_argument const& exp) {} | |
if (duration_str == "off") | |
{ | |
} | |
else if (duration_str == "now") | |
{ | |
} | |
std::stringstream ss(duration_str); | |
string str; | |
int seconds = 0; | |
char type; | |
int size; | |
while (std::getline(ss, str, ' ')) | |
{ | |
remove_if(str.begin(), str.end(), isspace); | |
if (str.size() == 0) continue; | |
if (sscanf(str.c_str(), "%d%c", &size, &type) != 2) | |
{ | |
throw std::invalid_argument("invalid duration format: " + str); | |
} | |
if (type == 'w' || type == 'W') { seconds += size * 7 * 24 * 60 * 60; } | |
else if (type == 'd' || type == 'D') { seconds += size * 24 * 60 * 60; } | |
else if (type == 'h' || type == 'H') { seconds += size * 60 * 60; } | |
else if (type == 'm' || type == 'M') { seconds += size * 60; } | |
else if (type == 's' || type == 'S') { seconds += size; } | |
else | |
{ | |
throw std::invalid_argument("invalid duration format: " + str); | |
} | |
} | |
auto start_tp = chr::system_clock::now() - chr::seconds(seconds); | |
retur chr::duration_cast<chr::seconds>(start_tp.time_since_epoch()).count(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment