Skip to content

Commit

Permalink
mu-utils: support UTC in parse_date_time
Browse files Browse the repository at this point in the history
Parsing dates known to be in UTC.
  • Loading branch information
djcb committed Aug 21, 2023
1 parent f73aad2 commit c1950ae
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
12 changes: 10 additions & 2 deletions lib/utils/mu-utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ fixup_month(struct tm* tbuf)


Option<::time_t>
Mu::parse_date_time(const std::string& dstr, bool is_first)
Mu::parse_date_time(const std::string& dstr, bool is_first, bool utc)
{
struct tm tbuf{};
GDateTime *dtime{};
Expand Down Expand Up @@ -442,12 +442,20 @@ Mu::parse_date_time(const std::string& dstr, bool is_first)
return Nothing;

fixup_month(&tbuf);
dtime = g_date_time_new_local(tbuf.tm_year + 1900,
dtime = utc ?
g_date_time_new_utc(tbuf.tm_year + 1900,
tbuf.tm_mon + 1,
tbuf.tm_mday,
tbuf.tm_hour,
tbuf.tm_min,
tbuf.tm_sec) :
g_date_time_new_local(tbuf.tm_year + 1900,
tbuf.tm_mon + 1,
tbuf.tm_mday,
tbuf.tm_hour,
tbuf.tm_min,
tbuf.tm_sec);

t = g_date_time_to_unix(dtime);
g_date_time_unref(dtime);

Expand Down
5 changes: 3 additions & 2 deletions lib/utils/mu-utils.hh
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ auto mu_join(Range&& range, std::string_view sepa) {
}

template <typename T>
auto mu_time(T t, bool use_utc=false) {
std::tm mu_time(T t={}, bool use_utc=false) {
::time_t tt{static_cast<::time_t>(t)};
return use_utc ? fmt::gmtime(tt) : fmt::localtime(tt);
}
Expand Down Expand Up @@ -253,10 +253,11 @@ static inline bool mu_print_encoded(fmt::format_string<T...> frm, T&&... args) n
* so 2018-05-05 is equivalent to 20180505.
* @param first whether to fill out incomplete dates to the start (@true) or the
* end (@false); ie. either 1972 -> 197201010000 or 1972 -> 197212312359
* @param use_utc interpret @param date as UTC
*
* @return the corresponding time_t or Nothing if parsing failed.
*/
Option<::time_t> parse_date_time(const std::string& date, bool first);
Option<::time_t> parse_date_time(const std::string& date, bool first, bool use_utc=false);

/**
* Crudely convert HTML to plain text. This attempts to scrape the
Expand Down

0 comments on commit c1950ae

Please sign in to comment.