64 lines
1.5 KiB
C++
64 lines
1.5 KiB
C++
|
|
#include "ml_date.h"
|
|
|
|
long now() {
|
|
// get-universal-time
|
|
time_t t = std::time(0);
|
|
long int now = static_cast<long int>(t);
|
|
|
|
return now;
|
|
}
|
|
|
|
std::string date_to_string(const long datetime, const std::string format) {
|
|
// std::locale::global(std::locale("en-US.UTF8"));
|
|
|
|
time_t timestamp = datetime;
|
|
char mbstr[128];
|
|
|
|
if (std::strftime(mbstr, sizeof(mbstr), format.c_str(), std::localtime(×tamp))) {
|
|
std::string result = {mbstr};
|
|
return result;
|
|
}
|
|
// TODO exception here
|
|
return "invalid argument";
|
|
}
|
|
|
|
|
|
std::istringstream in_ss;
|
|
long string_to_date(const std::string &datestr, const std::string &format) {
|
|
// format for example "%d.%m.%Y";
|
|
|
|
in_ss.clear();
|
|
in_ss.str(datestr);
|
|
|
|
date::sys_seconds tp;
|
|
date::from_stream(in_ss, format.c_str(), tp);
|
|
return tp.time_since_epoch().count();
|
|
}
|
|
|
|
long add_to_date(const long datetime, const long quantity, const std::string &part) {
|
|
// part is one of 'year', 'month', 'day', 'hour', 'minute' or 'second'
|
|
|
|
// very basic implementation, just for now - no timezones DST etc
|
|
time_t base = datetime;
|
|
struct tm *tm = localtime(&base);
|
|
|
|
if (part == "year") {
|
|
tm->tm_year += quantity;
|
|
} else if (part == "month") {
|
|
tm->tm_mon += quantity;
|
|
} else if (part == "day") {
|
|
tm->tm_mday += quantity;
|
|
} else if (part == "hour") {
|
|
tm->tm_hour += quantity;
|
|
} else if (part == "minute") {
|
|
tm->tm_min += quantity;
|
|
} else if (part == "second") {
|
|
tm->tm_sec += quantity;
|
|
} else {
|
|
// TODO exception here
|
|
}
|
|
|
|
return mktime(tm);
|
|
}
|