#ifndef _DATETIME_HELPERS_H_
#define _DATETIME_HELPERS_H_
#include <time.h>
#include <sstream>
/// \brief Date-time utility methods
class DateTimeHelpers
{
public:
/// \brief Create a unix timestamp from individual time components.
static time_t MKTimestamp(int year, int month, int day, int hour, int min, int sec)
{
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = gmtime(&rawtime); // NOLINT(runtime/threadsafe_fn)
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day;
timeinfo->tm_hour = hour;
timeinfo->tm_min = min;
timeinfo->tm_sec = sec;
timeinfo->tm_isdst = 0; // disable daylight saving time
time_t ret = mktime(timeinfo);
return ret;
}
static time_t GetGMTTimestamp()
{
time_t rawTime = 0;
time(&rawTime);
struct tm* pTm;
pTm = gmtime(&rawTime); // NOLINT(runtime/threadsafe_fn)
return mktime(pTm);
}
/// \brief Parse unix time from a string in the form yyyy-mm-dd hh:mm:ss (ex: 2015-11-16 09:43:36Z)
static time_t GetDateTime(const std::string pstr)
{
// yyyy-mm-dd hh:mm:ss
// example 2015-11-16 09:43:36Z
int m, d, y, h, min, sec;
std::istringstream istr(pstr);
istr >> y;
istr.ignore();
istr >> m;
istr.ignore();
istr >> d;
istr.ignore();
istr >> h;
istr.ignore();
istr >> min;
istr.ignore();
istr >> sec;
time_t t;
t = MKTimestamp(y, m, d, h, min, sec);
return t;
}
};
#endif // _DATETIME_HELPERS_H_