From: Mats Klepsland Date: Fri, 30 Oct 2015 08:14:54 +0000 (+0100) Subject: util-time: add function to convert tm to time_t X-Git-Tag: suricata-3.2beta1~291 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6c1c53b5a115ccd2859691a29dade9c6b8d981bc;p=thirdparty%2Fsuricata.git util-time: add function to convert tm to time_t Add function SCMkTimeUtc to convert broken-down time to Unix epoch in UTC. --- diff --git a/src/util-time.c b/src/util-time.c index 40de6b8173..352c041fad 100644 --- a/src/util-time.c +++ b/src/util-time.c @@ -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; +} diff --git a/src/util-time.h b/src/util-time.h index 6efce2f7b2..2b4944528a 100644 --- a/src/util-time.h +++ b/src/util-time.h @@ -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__ */