Commit 0aaba7a4 authored by Dmitry Frank's avatar Dmitry Frank Committed by Cesanta Bot

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
parent 3d6b568c
......@@ -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
......
......@@ -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 */
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment