UTC conversion to and from time_t
authorArjen Baart <arjen@andromeda.nl>
Thu, 25 Jun 2020 18:15:12 +0000 (20:15 +0200)
committerArjen Baart <arjen@andromeda.nl>
Thu, 25 Jun 2020 18:15:12 +0000 (20:15 +0200)
src/date.h
src/utc.cpp
test/utc_convert.cpp
test/utc_convert.exp

index ee5ba12..0449441 100644 (file)
@@ -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();
index 59d87d7..4bc4c36 100644 (file)
@@ -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;
index f9dbb87..bbcda81 100644 (file)
@@ -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;
 }
 
index bdbfcef..1c2c1af 100644 (file)
@@ -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)