From f8e8aec6e02a5b9a2aee2be40ce47632a08c2908 Mon Sep 17 00:00:00 2001 From: cyberman54 Date: Thu, 20 Jan 2022 17:37:12 +0100 Subject: [PATCH] timekeeper.cpp: add mkgmtime() --- src/timekeeper.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/timekeeper.cpp b/src/timekeeper.cpp index ef614624..6cb55d76 100644 --- a/src/timekeeper.cpp +++ b/src/timekeeper.cpp @@ -366,5 +366,38 @@ time_t compileTime(const String compile_date) { secs = mktime(&t); } + return secs; +} + +static bool IsLeapYear(short year) { + if (year % 4 != 0) + return false; + if (year % 100 != 0) + return true; + return (year % 400) == 0; +} + +// convert UTC tm time to time_t epoch time +time_t mkgmtime(const struct tm *ptm) { + const int SecondsPerMinute = 60; + const int SecondsPerHour = 3600; + const int SecondsPerDay = 86400; + const int DaysOfMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + time_t secs = 0; + // tm_year is years since 1900 + int year = ptm->tm_year + 1900; + for (int y = 1970; y < year; ++y) { + secs += (IsLeapYear(y) ? 366 : 365) * SecondsPerDay; + } + // tm_mon is month from 0..11 + for (int m = 0; m < ptm->tm_mon; ++m) { + secs += DaysOfMonth[m] * SecondsPerDay; + if (m == 1 && IsLeapYear(year)) + secs += SecondsPerDay; + } + secs += (ptm->tm_mday - 1) * SecondsPerDay; + secs += ptm->tm_hour * SecondsPerHour; + secs += ptm->tm_min * SecondsPerMinute; + secs += ptm->tm_sec; return secs; } \ No newline at end of file