76 lines
2.2 KiB
C++
76 lines
2.2 KiB
C++
#include "TimeStamp.h"
|
|
#include "lib/utils/datetime.h"
|
|
#include <boost/date_time/posix_time/time_formatters.hpp>
|
|
#include <google/protobuf/timestamp.pb.h>
|
|
|
|
namespace bts::core {
|
|
|
|
using std::uint32_t;
|
|
using std::uint8_t;
|
|
|
|
static bool is_valid_ymd(uint32_t year, uint8_t month, uint8_t day) {
|
|
return year >= 1970 && month >= 1 && month <= 12 && day >= 1 && day <= 31;
|
|
}
|
|
|
|
TimeStamp::TimeStamp(
|
|
uint32_t year,
|
|
uint8_t month,
|
|
uint8_t day,
|
|
uint8_t hour,
|
|
uint8_t minute,
|
|
uint8_t second) {
|
|
bts_assert_msgf(
|
|
is_valid_ymd(year, month, day), "Invalid timestamp {}/{}/{} (y/m/d)",
|
|
year, month, day);
|
|
std::tm date = {};
|
|
date.tm_year = year - 1900;
|
|
date.tm_mon = month - 1;
|
|
date.tm_mday = day;
|
|
date.tm_hour = hour;
|
|
date.tm_min = minute;
|
|
date.tm_sec = second;
|
|
auto time = std::chrono::system_clock::from_time_t(mktime(&date));
|
|
auto duration = time.time_since_epoch();
|
|
value_ =
|
|
std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count();
|
|
}
|
|
|
|
bool TimeStamp::from_ymd(
|
|
uint32_t year, uint8_t month, uint8_t day, TimeStamp *result) {
|
|
if (!is_valid_ymd(year, month, day)) {
|
|
return false;
|
|
}
|
|
*result = TimeStamp{year, month, day};
|
|
return true;
|
|
}
|
|
|
|
void TimeStamp::to_protobuf(google::protobuf::Timestamp &ts) const {
|
|
ts.set_seconds(seconds());
|
|
bts_assert(nanos() >= seconds() * 1'000'000'000);
|
|
ts.set_nanos(nanos() - seconds() * 1'000'000'000);
|
|
}
|
|
|
|
TimeStamp TimeStamp::from_iso_string(const std::string &iso_string) {
|
|
auto ptime = datetime::parse_iso_date_time_string(iso_string);
|
|
return from_ptime(ptime);
|
|
}
|
|
|
|
std::string TimeStamp::to_iso_string() const {
|
|
return boost::posix_time::to_iso_string(to_ptime());
|
|
}
|
|
|
|
std::ostream &operator<<(std::ostream &out, const TimeStamp &ts) noexcept {
|
|
out << ts.to_iso_string();
|
|
return out;
|
|
}
|
|
|
|
TimeStamp TimeStamp::from_ptime(boost::posix_time::ptime t) {
|
|
// time_t is Unix time: number of seconds since epoch Jan 1, 1970
|
|
auto epoch_pt =
|
|
t - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1));
|
|
auto epoch_nanos = epoch_pt.total_nanoseconds();
|
|
return TimeStamp{static_cast<std::uint64_t>(epoch_nanos)};
|
|
}
|
|
|
|
} // namespace bts::core
|