Files
spark/src/lib/utils/datetime.cpp
T

544 lines
16 KiB
C++

#include "datetime.h"
#include "TimeStamp.h"
#include "bts_assert.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <sstream>
#include <time.h>
namespace bts {
namespace datetime {
const boost::gregorian::date anchor(1970, boost::gregorian::Jan, 1);
const uint64_t anchor_ticks = 621355968000000000;
const uint64_t micros_per_day = 86400000000;
const uint64_t ticks_per_micro = 10;
const uint64_t ticks_per_day = micros_per_day * ticks_per_micro;
const uint64_t ticks_mask = 0x3FFFFFFFFFFFFFFF;
// DateTimeKinds
const uint64_t KindUnspecified = 0x0000000000000000;
const uint64_t KindUtc = 0x4000000000000000;
const uint64_t KindLocal = 0x8000000000000000;
unsigned long long ptime_to_ll(PTime const &t, uint64_t const &kind) {
uint64_t days = (t.date() - anchor).days();
uint64_t usecs = t.time_of_day().total_microseconds();
uint64_t ticks =
anchor_ticks + usecs * ticks_per_micro + days * ticks_per_day;
return (ticks & ticks_mask) | kind;
}
unsigned long long ptime_to_ll(PTime const &t) {
return ptime_to_ll(t, KindUnspecified);
}
LLDateTime ll_now() {
return ptime_to_ll(
boost::posix_time::microsec_clock::universal_time(), KindUtc);
}
LLDateTime ll_local_now() {
return ptime_to_ll(
boost::posix_time::microsec_clock::local_time(), KindLocal);
}
long unix_now() {
return (boost::posix_time::microsec_clock::universal_time() - PTime(anchor))
.total_microseconds() /
(long)1E6;
}
std::chrono::system_clock::time_point utc_ll_to_timepoint(
unsigned long long ll) {
auto us_since_epoch = ((ll & ticks_mask) - anchor_ticks) / ticks_per_micro;
return std::chrono::system_clock::time_point(
std::chrono::microseconds(us_since_epoch));
}
long long ll_diff_in_us(unsigned long long ll1, unsigned long long ll2) {
#ifndef NO_CPP0X
auto p1 = ll_to_ptime(ll1);
auto p2 = ll_to_ptime(ll2); // NOLINT
return (p2 - p1).total_microseconds();
#else
return 0;
#endif
}
long long ll_diff_in_seconds(unsigned long long ll1, unsigned long long ll2) {
#ifndef NO_CPP0X
auto p1 = ll_to_ptime(ll1);
auto p2 = ll_to_ptime(ll2); // NOLINT
return (p2 - p1).total_seconds();
#else
return 0;
#endif
}
long long ptime_diff_in_us(PTime const &t1, PTime const &t2) {
return (t1 - t2).total_microseconds();
}
long long ptime_diff_in_ms(PTime const &t1, PTime const &t2) {
return (t1 - t2).total_milliseconds();
}
long long ptime_diff_in_secs(PTime const &t1, PTime const &t2) {
return (t1 - t2).total_seconds();
}
PTime timestamp_to_ptime(utils::TimeStamp const &t) {
auto now_ts = utils::TimeStamp::now();
auto now = datetime::local_now();
auto delta = (now_ts - t).milliseconds();
return now - boost::posix_time::milliseconds(delta);
}
utils::TimeStamp ptime_to_timestamp(PTime const &t) {
auto now_ts = utils::TimeStamp::now();
auto now = datetime::now();
auto delta = (now - t).total_milliseconds();
return now_ts.shift_ms(delta);
}
long long usecs_since(PTime const &t1) {
return (boost::posix_time::microsec_clock::universal_time() - t1)
.total_microseconds();
}
long long msecs_since(PTime const &t1) {
return (boost::posix_time::microsec_clock::universal_time() - t1)
.total_milliseconds();
}
PTime now() { return boost::posix_time::microsec_clock::universal_time(); }
PTime local_now() { return boost::posix_time::microsec_clock::local_time(); }
PTime make_ptime(int year, int month, int day) {
// January=1
bts_assert_d(month > 0);
boost::gregorian::date dt(year, boost::gregorian::greg_month(month), day);
return PTime(dt);
}
PTime make_ptime(
int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond) {
boost::gregorian::date dt(year, boost::gregorian::greg_month(month), day);
return PTime(
dt, boost::posix_time::time_duration(hour, minute, second) +
boost::posix_time::milliseconds(millisecond));
}
PTime ll_to_ptime(LLDateTime ll) {
ll &= ticks_mask;
uint64_t ticks_part = ll % ticks_per_day;
uint64_t days_part = (ll - anchor_ticks) / ticks_per_day;
return PTime(
anchor + boost::gregorian::date_duration(days_part),
boost::posix_time::time_duration(
boost::posix_time::microseconds(ticks_part / ticks_per_micro)));
}
extern "C" BTS_EXPORT int ll_to_cstr(
LLDateTime ll, char *buffer, int buffer_sz) {
const int str_sz = sizeof("20121204-14:44:02.000");
bts_assert(buffer_sz >= str_sz);
auto str = FIX_timestamp(ll_to_ptime(ll));
bts_assert(str.size() == str_sz - 1);
memcpy(buffer, &str[0], str.size());
buffer[str.size()] = '\0';
return str.size();
}
std::string time_string(PTime const &t) {
int hours = t.time_of_day().hours();
int minutes = t.time_of_day().minutes();
int seconds = t.time_of_day().seconds();
int whole_ms = seconds * 1000 + minutes * 1000 * 60 + hours * 1000 * 60 * 60;
int frac_ms = t.time_of_day().total_milliseconds() - whole_ms;
std::ostringstream out;
out << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2)
<< std::setfill('0') << minutes << ":" << std::setw(2)
<< std::setfill('0') << seconds << "." << std::setw(3)
<< std::setfill('0') << frac_ms;
return out.str();
}
std::string date_string(PTime const &t) {
std::string result(10, ' ');
sprintf(
&result[0], "%02d/%02d/%04d", t.date().month().as_number(),
t.date().day().as_number(), (unsigned short)t.date().year());
return result;
}
std::string iso_date_time_string(PTime const &t) {
return boost::posix_time::to_iso_extended_string(t);
}
PTime parse_iso_date_time_tz(const std::string &date) {
// example 1) 2022-10-27T09:30-5:00
// example 2) 2022-10-27T09:30+5:00
#ifdef _WIN32
struct tm tt = {0, 0, 0, 0, 0, 0, 0, 0, 0};
#else
struct tm tt = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
#endif
int tz_hours;
int tz_minutes;
int num_scanned = sscanf(
date.c_str(), "%4d-%2d-%2dT%2d:%2d:%2d%3d:%2d", &tt.tm_year, &tt.tm_mon,
&tt.tm_mday, &tt.tm_hour, &tt.tm_min, &tt.tm_sec, &tz_hours,
&tz_minutes);
bts_assert_msgf(
num_scanned == 8,
"Failed to parse iso8601 date from string '{}' (format must be "
"YYYY-MM-DDThh:mm:ss<+/->hh:ss)",
date);
tt.tm_mon -= 1;
tt.tm_year -= 1900;
tt.tm_isdst = -1;
return boost::posix_time::ptime_from_tm(tt) +
boost::posix_time::time_duration{tz_hours, tz_minutes, 0, 0};
}
PTime parse_iso_date_time_string(std::string const &t) {
constexpr const std::size_t time_idx = sizeof("YYYY-MM-DD") - 1;
auto actual_time_idx = t.find('T', time_idx);
if (actual_time_idx != std::string::npos) {
constexpr const std::size_t time_zone_idx =
time_idx + sizeof("HH:MM") - 1;
// time zone must be after time
bts_assert(actual_time_idx < time_zone_idx);
if (t.find('+', time_zone_idx) != std::string::npos ||
t.find('-', time_zone_idx) != std::string::npos) {
// date, time, and time zone
return parse_iso_date_time_tz(t);
}
// date and time (no time zone)
return boost::posix_time::from_iso_extended_string(t);
}
// date (no time or time zone)
return PTime{boost::gregorian::from_simple_string(t)};
}
std::string simple_date_time_string(PTime const &t) {
return boost::posix_time::to_simple_string(t);
}
PTime parse_simple_date_time_string(std::string const &t) {
if (t.find(' ') == t.npos)
return boost::posix_time::time_from_string(t + " 00:00:00");
else
return boost::posix_time::time_from_string(t);
}
PDuration parse_duration(std::string const &time_str) {
try {
return boost::posix_time::duration_from_string(time_str);
} catch (boost::bad_lexical_cast &) {
bts_assert(false);
return boost::posix_time::time_duration();
}
}
std::string FIX_date_time_string(PTime const &t) {
std::string result(strlen("20121204-14:44:02"), ' ');
sprintf(
&result[0], "%d%02d%02d-%02d:%02d:%02d", (unsigned short)t.date().year(),
t.date().month().as_number(), t.date().day().as_number(),
(int)t.time_of_day().hours(), (int)t.time_of_day().minutes(),
(int)t.time_of_day().seconds());
return result;
}
void FIX_timestamp(PTime const &t, std::string *out) {
int hours = t.time_of_day().hours();
int minutes = t.time_of_day().minutes();
int seconds = t.time_of_day().seconds();
int whole_ms = seconds * 1000 + minutes * 1000 * 60 + hours * 1000 * 60 * 60;
int frac_ms = t.time_of_day().total_milliseconds() - whole_ms;
out->resize(sizeof("20121204-14:44:02.000"));
#ifdef _WIN32
_snprintf(
&(*out)[0], out->size(), "%04d%02d%02d-%02d:%02d:%02d.%03d",
(int)t.date().year(), t.date().month().as_number(),
t.date().day().as_number(), hours, minutes, seconds, frac_ms);
#else
snprintf(
&(*out)[0], out->size(), "%04d%02d%02d-%02d:%02d:%02d.%03d",
(int)t.date().year(), t.date().month().as_number(),
t.date().day().as_number(), hours, minutes, seconds, frac_ms);
#endif
out->resize(out->size() - 1);
}
std::string FIX_timestamp(PTime const &t) {
std::string result;
FIX_timestamp(t, &result);
return result;
}
bool is_from_today(PTime const &time) {
return (
time.date() ==
boost::posix_time::microsec_clock::universal_time().date());
}
bool is_at_least_msecs_old(PTime const &time, uint64_t ms) {
PTime now = boost::posix_time::microsec_clock::universal_time();
return (now - time).total_milliseconds() >= (int64_t)ms;
}
bool is_at_least_secs_old(PTime const &time, uint64_t sec) {
PTime now = boost::posix_time::microsec_clock::universal_time();
return (now - time).total_seconds() >= (int64_t)sec;
}
bool is_at_least_mins_old(PTime const &time, uint64_t mins) {
PTime now = boost::posix_time::microsec_clock::universal_time();
return ((now - time).total_seconds() / 60) >= (int64_t)mins;
}
bool is_at_least_hours_old(PTime const &time, uint64_t hours) {
PTime now = boost::posix_time::microsec_clock::universal_time();
int64_t secs = (int64_t)((now - time).total_seconds());
return (secs / 60 / 60) >= (int64_t)hours;
}
bool is_at_least_days_old(PTime const &time, uint64_t days) {
return is_at_least_hours_old(time, days * 24);
}
LLDateTime ll_from_unix_epoch(long seconds) {
PTime result(anchor, boost::posix_time::seconds(seconds));
return ptime_to_ll(result, KindUnspecified);
}
LLDateTime ll_from_unix_epoch_ms(long long milliseconds) {
PTime result(anchor, boost::posix_time::millisec(milliseconds));
return ptime_to_ll(result, KindUnspecified);
}
void ll_to_parts(
LLDateTime ll_time,
int &year,
int &month,
int &day,
int &hour,
int &minute,
int &second,
int &millisecond) {
PTime t = ll_to_ptime(ll_time);
year = t.date().year();
month = t.date().month();
day = t.date().day();
hour = t.time_of_day().hours();
minute = t.time_of_day().minutes();
second = t.time_of_day().seconds();
int whole_ms = second * 1000 + minute * 1000 * 60 + hour * 1000 * 60 * 60;
millisecond = t.time_of_day().total_milliseconds() - whole_ms;
}
LLDateTime ll_from_parts(
int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond) {
return ptime_to_ll(make_ptime(
year, month, day, hour, minute, second, millisecond)); // NOLINT
}
LLDateTime ll_from_date(const Date &date) {
if (date.year == 0 && date.day == 0 && date.month == 0) {
return 0;
}
return ll_from_parts(date.year, date.month, date.day, 0, 0, 0, 0);
}
Date ll_to_date(LLDateTime time) {
Date date;
int year, month, day, unused;
ll_to_parts(time, year, month, day, unused, unused, unused, unused);
date.year = year;
date.month = month;
date.day = day;
return date;
}
bool is_local_time_sunday() {
auto now = local_now();
return now.date().day_of_week() == boost::date_time::Sunday;
}
bool is_local_time_between(int hh_start, int mm_start, int hh_end, int mm_end) {
using namespace boost::posix_time;
auto now = local_now();
auto start = ptime(now.date(), hours(hh_start) + minutes(mm_start));
auto end = ptime(now.date(), hours(hh_end) + minutes(mm_end));
return (now >= start && now <= end);
}
struct UtcTimeStamp {
int hour;
int min;
int sec;
int msec;
int day;
int month;
int year;
};
struct UtcTimeStampConvertor {
static UtcTimeStamp convert(const std::string &value) {
bool haveMilliseconds = false;
switch (value.size()) {
case 21:
haveMilliseconds = true;
case 17:
break;
default:
bts_assert(false);
}
int i = 0;
int c = 0;
for (c = 0; c < 8; ++c)
if (!isdigit(value[i++]))
bts_assert(false);
if (value[i++] != '-')
bts_assert(false);
for (c = 0; c < 2; ++c)
if (!isdigit(value[i++]))
bts_assert(false);
if (value[i++] != ':')
bts_assert(false);
for (c = 0; c < 2; ++c)
if (!isdigit(value[i++]))
bts_assert(false);
if (value[i++] != ':')
bts_assert(false);
for (c = 0; c < 2; ++c)
if (!isdigit(value[i++]))
bts_assert(false);
if (haveMilliseconds) {
if (value[i++] != '.')
bts_assert(false);
for (c = 0; c < 3; ++c)
if (!isdigit(value[i++]))
bts_assert(false);
}
int year, mon, mday, hour, min, sec, millis;
i = 0;
year = value[i++] - '0';
year = 10 * year + value[i++] - '0';
year = 10 * year + value[i++] - '0';
year = 10 * year + value[i++] - '0';
mon = value[i++] - '0';
mon = 10 * mon + value[i++] - '0';
if (mon < 1 || 12 < mon)
bts_assert(false);
mday = value[i++] - '0';
mday = 10 * mday + value[i++] - '0';
if (mday < 1 || 31 < mday)
bts_assert(false);
++i; // skip '-'
hour = value[i++] - '0';
hour = 10 * hour + value[i++] - '0';
// No check for >= 0 as no '-' are converted here
if (23 < hour)
bts_assert(false);
++i; // skip ':'
min = value[i++] - '0';
min = 10 * min + value[i++] - '0';
// No check for >= 0 as no '-' are converted here
if (59 < min)
bts_assert(false);
++i; // skip ':'
sec = value[i++] - '0';
sec = 10 * sec + value[i++] - '0';
// No check for >= 0 as no '-' are converted here
if (60 < sec)
bts_assert(false);
if (haveMilliseconds) {
millis =
(100 * (value[i + 1] - '0') + 10 * (value[i + 2] - '0') +
(value[i + 3] - '0'));
} else
millis = 0;
return UtcTimeStamp{hour, min, sec, millis, mday, mon, year};
}
};
PTime parse_FIX_timestamp(const std::string &ts_str) {
auto ts = UtcTimeStampConvertor::convert(ts_str);
boost::gregorian::date dt(ts.year, ts.month, ts.day);
// fucking boost. unbelieavable.
auto ticks_per_second =
boost::posix_time::time_duration::rep_type::res_adjust();
boost::posix_time::time_duration td(
ts.hour, ts.min, ts.sec, ts.msec * (ticks_per_second / 1000));
return PTime(dt, td);
}
#ifndef NO_CPP0X
extern "C" BTS_EXPORT LLDateTime ll_today() {
return datetime::ll_from_date(today());
}
BTS_EXPORT Date today() {
auto now = datetime::now();
Date date;
date.year = now.date().year();
date.month = now.date().month();
date.day = now.date().day();
return date;
}
BTS_EXPORT Date add_days(Date indate, int days) {
boost::gregorian::date dt(indate.year, indate.month, indate.day);
auto adjusted_dt = dt + boost::gregorian::days(days);
Date date(adjusted_dt.year(), adjusted_dt.month(), adjusted_dt.day());
return date;
}
extern "C" BTS_EXPORT LLDateTime ll_yesterday() {
auto now = datetime::now() - boost::gregorian::days(1);
return datetime::ll_from_parts(
now.date().year(), now.date().month(), now.date().day(), 0, 0, 0, 0);
}
#endif
} // namespace datetime
} // namespace bts