mlisp/ml_date.cpp

59 lines
1.4 KiB
C++

#include "ml_date.h"
int now() {
// get-universal-time
time_t t = std::time(0);
long int now = static_cast<long int>(t);
return (int) now;
}
std::string date_to_string(const int 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(&timestamp))) {
std::string result = {mbstr};
return result;
}
// TODO exception here
}
int string_to_date(const std::string &datestr, const std::string &format) {
// format for example "%d.%m.%Y";
std::istringstream in{datestr.c_str()};
date::sys_seconds tp;
in >> date::parse(format, tp);
return (int) tp.time_since_epoch().count();
}
int add_to_date(const int datetime, const int quantity, const std::string &part) {
// part is one of 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'
// 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 (int) mktime(tm);
}