]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
util-time: add function to convert tm to time_t
authorMats Klepsland <mats.klepsland@gmail.com>
Fri, 30 Oct 2015 08:14:54 +0000 (09:14 +0100)
committerVictor Julien <victor@inliniac.net>
Sun, 25 Sep 2016 20:35:34 +0000 (22:35 +0200)
Add function SCMkTimeUtc to convert broken-down time to Unix epoch in UTC.

src/util-time.c
src/util-time.h

index 40de6b817359c50dbad59649d411ec76b45ecd5c..352c041fad7abe2d72676e5277691ac55ba0af4b 100644 (file)
@@ -354,3 +354,41 @@ void CreateTimeString (const struct timeval *ts, char *str, size_t size)
 }
 
 #endif /* defined(__OpenBSD__) */
+
+/**
+ * \brief Convert broken-down time to seconds since Unix epoch.
+ *
+ * This function is based on: http://www.catb.org/esr/time-programming
+ * (released to the public domain).
+ *
+ * \param tp Pointer to broken-down time.
+ *
+ * \retval Seconds since Unix epoch.
+ */
+time_t SCMkTimeUtc (struct tm *tp)
+{
+    time_t result;
+    long year;
+#define MONTHSPERYEAR 12
+    static const int mdays[MONTHSPERYEAR] =
+            { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+
+    year = 1900 + tp->tm_year + tp->tm_mon / MONTHSPERYEAR;
+    result = (year - 1970) * 365 + mdays[tp->tm_mon % MONTHSPERYEAR];
+    result += (year - 1968) / 4;
+    result -= (year - 1900) / 100;
+    result += (year - 1600) / 400;
+    if ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0) &&
+            (tp->tm_mon % MONTHSPERYEAR) < 2)
+        result--;
+    result += tp->tm_mday - 1;
+    result *= 24;
+    result += tp->tm_hour;
+    result *= 60;
+    result += tp->tm_min;
+    result *= 60;
+    result += tp->tm_sec;
+    if (tp->tm_gmtoff)
+        result -= tp->tm_gmtoff;
+    return result;
+}
index 6efce2f7b2f4bee9fb1b48515798b1548ea96a66..2b4944528ab42aa001d78e2ead22d38efdb4633b 100644 (file)
@@ -53,6 +53,7 @@ int TimeModeIsLive(void);
 struct tm *SCLocalTime(time_t timep, struct tm *result);
 void CreateTimeString (const struct timeval *ts, char *str, size_t size);
 void CreateIsoTimeString (const struct timeval *ts, char *str, size_t size);
+time_t SCMkTimeUtc (struct tm *tp);
 
 #endif /* __UTIL_TIME_H__ */