chore: Support timezones when parsing iso dates

This is needed because FTX (and perhaps other exchanges) format
expirations with timezones
This commit is contained in:
John Colvin committed 2023-01-04 13:35:38 -05:00
1 parent 43ba30365a
commit 0dc278eed5
2 files changed
+39 -3

No files matched your search

+38 -3
View File
@@ -6,6 +6,7 @@
#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 {
@@ -186,11 +187,45 @@ 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
struct tm tt = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
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) {
if (t.find('T') == t.npos)
return boost::posix_time::from_iso_extended_string(t + "T00:00:00");
else
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) {