Add cs_timegm

Which is a slightly modified version from
https://stackoverflow.com/questions/283166/easy-way-to-convert-a-struct-tm-expressed-in-utc-to-time-t-type

PUBLISHED_FROM=b73f920ca42c45473c23337782e815306bdf69f1
This commit is contained in:
Dmitry Frank 2017-09-12 19:08:43 +03:00 committed by Cesanta Bot
parent 3d6b568c6e
commit 0aaba7a461
2 changed files with 43 additions and 0 deletions

View File

@ -780,6 +780,41 @@ double cs_time(void) {
#endif /* _WIN32 */
return now;
}
double cs_timegm(const struct tm *tm) {
/* Month-to-day offset for non-leap-years. */
static const int month_day[12] = {0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334};
/* Most of the calculation is easy; leap years are the main difficulty. */
int month = tm->tm_mon % 12;
int year = tm->tm_year + tm->tm_mon / 12;
int year_for_leap;
int64_t rt;
if (month < 0) { /* Negative values % 12 are still negative. */
month += 12;
--year;
}
/* This is the number of Februaries since 1900. */
year_for_leap = (month > 1) ? year + 1 : year;
rt =
tm->tm_sec /* Seconds */
+
60 *
(tm->tm_min /* Minute = 60 seconds */
+
60 * (tm->tm_hour /* Hour = 60 minutes */
+
24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
+ 365 * (year - 70) /* Year = 365 days */
+ (year_for_leap - 69) / 4 /* Every 4 years is leap... */
- (year_for_leap - 1) / 100 /* Except centuries... */
+ (year_for_leap + 299) / 400))); /* Except 400s. */
return rt < 0 ? -1 : (double) rt;
}
#ifdef MG_MODULE_LINES
#line 1 "common/cs_endian.h"
#endif

View File

@ -1797,6 +1797,8 @@ void cs_hmac_sha1(const unsigned char *key, size_t key_len,
#ifndef CS_COMMON_CS_TIME_H_
#define CS_COMMON_CS_TIME_H_
#include <time.h>
/* Amalgamated: #include "common/platform.h" */
#ifdef __cplusplus
@ -1806,6 +1808,12 @@ extern "C" {
/* Sub-second granularity time(). */
double cs_time(void);
/*
* Similar to (non-standard) timegm, converts broken-down time into the number
* of seconds since Unix Epoch.
*/
double cs_timegm(const struct tm *tm);
#ifdef __cplusplus
}
#endif /* __cplusplus */