Skip to content

Commit

Permalink
dt: tm <-> datetime conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
mcspr committed Aug 22, 2024
1 parent 24ebcb8 commit a803356
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
24 changes: 24 additions & 0 deletions code/espurna/datetime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,34 @@ Seconds to_seconds(const Date& date, const HhMmSs& hh_mm_ss) noexcept {
return out;
}

tm DateHhMmSs::c_value() const noexcept {
tm out{};
out.tm_isdst = -1;

out.tm_year = year - 1900;
out.tm_mon = month - 1;
out.tm_mday = day;

out.tm_hour = hours;
out.tm_min = minutes;
out.tm_sec = seconds;

return out;
}

Seconds to_seconds(const tm& t) noexcept {
return to_seconds(make_date(t), make_hh_mm_ss(t));
}

Seconds to_seconds(const DateHhMmSs& datetime, bool utc) noexcept {
if (utc) {
return to_seconds(Date(datetime), HhMmSs(datetime));
}

auto c_value = datetime.c_value();
return Seconds{ mktime(&c_value) };
}

Context make_context(Seconds seconds) {
return make_context(seconds.count());
}
Expand Down
7 changes: 7 additions & 0 deletions code/espurna/datetime.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ constexpr HhMmSs make_hh_mm_ss(const tm& t) {
};
}

struct DateHhMmSs : public Date, public HhMmSs {
tm c_value() const noexcept;
};

Date from_days(const Days&) noexcept;

// on esp8266 this is a usually an internal timestamp timeshift'ed with `micros64()`
Expand Down Expand Up @@ -185,6 +189,9 @@ constexpr Weekday next(Weekday day) {
Seconds to_seconds(const Date&, const HhMmSs&) noexcept;
Seconds to_seconds(const tm&) noexcept;

// Either local or UTC conversion
Seconds to_seconds(const DateHhMmSs&, bool) noexcept;

// main use-case is scheduler, and it needs both tm results
struct Context {
time_t timestamp;
Expand Down

0 comments on commit a803356

Please sign in to comment.