From b4589d20d311957f5190532400e870ff094bfa34 Mon Sep 17 00:00:00 2001 From: Arjen Baart Date: Thu, 25 Jun 2020 20:15:12 +0200 Subject: [PATCH] UTC conversion to and from time_t --- src/date.h | 3 +++ src/utc.cpp | 27 +++++++++++++++++++++++++++ test/utc_convert.cpp | 18 ++++++++++++++++++ test/utc_convert.exp | 4 ++++ 4 files changed, 52 insertions(+) diff --git a/src/date.h b/src/date.h index ee5ba12..0449441 100644 --- a/src/date.h +++ b/src/date.h @@ -380,6 +380,7 @@ public: } UTC(const String s); + UTC(const time_t clock); UTC(date dt, hour tm) { d = dt; @@ -396,6 +397,8 @@ public: return t; } + time_t to_time_t(); + bool proper() { return d.proper() && t.proper(); diff --git a/src/utc.cpp b/src/utc.cpp index 59d87d7..4bc4c36 100644 --- a/src/utc.cpp +++ b/src/utc.cpp @@ -73,6 +73,33 @@ UTC::UTC(String s) t.seconds = 0; } +UTC::UTC(const time_t clock) +{ + struct tm *tp; + + tp = localtime(&clock); + t = hour(tp->tm_hour, tp->tm_min, tp->tm_sec); + d = date(tp->tm_mday, tp->tm_mon+1, tp->tm_year+1900); +} + +time_t UTC::to_time_t() +{ + struct tm tp; + time_t clock; + + tp.tm_year = d.Year() - 1900; + tp.tm_mon = d.Month() - 1; + tp.tm_mday = d.Day(); + tp.tm_hour = t.Hour(); + tp.tm_min = t.Minute(); + tp.tm_sec = t.Second(); + tp.tm_isdst = -1; + + clock = mktime(&tp); + + return clock; +} + UTC Now(bool local) { long clock; diff --git a/test/utc_convert.cpp b/test/utc_convert.cpp index f9dbb87..bbcda81 100644 --- a/test/utc_convert.cpp +++ b/test/utc_convert.cpp @@ -33,6 +33,24 @@ int main() assert(formatted == "2019-10-23 23:45:00"); + String s4("22-10-2020 16:40"); + UTC u4(s4); + time_t t4; + + std::cout << "Contructor from String " << s4 << " : " << u4 << "\n"; + t4 = u4.to_time_t(); + std::cout << "Converted to time_t: " << t4 << " seconds since Epoch\n"; + assert(t4 == 1603377600); + + UTC u5(t4); + std::cout << "Constructed from time_t " << t4 << " : " << u5 << "\n"; + assert(u5 == u4); + + UTC u6; + u6 = t4; + std::cout << "Assigned from time_t " << t4 << " : " << u6 << "\n"; + assert(u6 == u4); + return 0; } diff --git a/test/utc_convert.exp b/test/utc_convert.exp index bdbfcef..1c2c1af 100644 --- a/test/utc_convert.exp +++ b/test/utc_convert.exp @@ -2,4 +2,8 @@ Contructor with date = 15-9-2002, hour = 15:23:46: 15-09-2002 15:23:46 Formatted with default format: 2002-09-15 15:23:46 Contructor from String 23-10-2019 23:45 : 23-10-2019 23:45:00 Formatted with default format: 2019-10-23 23:45:00 +Contructor from String 22-10-2020 16:40 : 22-10-2020 16:40:00 +Converted to time_t: 1603377600 seconds since Epoch +Constructed from time_t 1603377600 : 22-10-2020 16:40:00 +Assigned from time_t 1603377600 : 22-10-2020 16:40:00 PASS utc_convert (exit status: 0) -- 2.20.1