summaryrefslogtreecommitdiff
path: root/src/localtime.c
diff options
context:
space:
mode:
authorantirez <antirez@gmail.com>2018-07-04 13:25:55 +0200
committerantirez <antirez@gmail.com>2018-07-04 13:25:55 +0200
commit0c12cbedbb1626597acf2f43718c6b52fc42d08a (patch)
treec25e0bdfbdc9265bffed037a47174246059642c0 /src/localtime.c
parent06ca400f95aca07a3807e16b061415d82c927c64 (diff)
downloadredis-0c12cbedbb1626597acf2f43718c6b52fc42d08a.tar.gz
Localtime: compute year, month and day of the month.
Diffstat (limited to 'src/localtime.c')
-rw-r--r--src/localtime.c26
1 files changed, 26 insertions, 0 deletions
diff --git a/src/localtime.c b/src/localtime.c
index a92d7464c..d4090e63c 100644
--- a/src/localtime.c
+++ b/src/localtime.c
@@ -69,4 +69,30 @@ void nolocks_localtime(struct tm *tmp, time_t t, time_t tz, int dst) {
* where sunday = 0, so to calculate the day of the week we have to add 4
* and take the modulo by 7. */
tmp->tm_wday = (days+4)%7;
+
+ /* Calculate the current year. */
+ tmp->tm_year = 1970;
+ while(1) {
+ /* Leap years have one year more. */
+ time_t days_this_year = 365 + is_leap_year(tmp->tm_year);
+ if (days_this_year > days) break;
+ days -= days_this_year;
+ tmp->tm_year++;
+ }
+ tmp->tm_yday = days; /* Number of day of the current year. */
+
+ /* We need to calculate in which month and day of the month we are. To do
+ * so we need to skip days according to how many days there are in each
+ * month, and adjust for the leap year that has one more day in February. */
+ int mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
+ mdays[1] += is_leap_year(tmp->tm_year);
+
+ tmp->tm_mon = 0;
+ while(days >= mdays[tmp->tm_mon]) {
+ days -= mdays[tmp->tm_mon];
+ tmp->tm_mon++;
+ }
+
+ tmp->tm_mday = days;
+ tmp->tm_year -= 1900; /* Surprisingly tm_year is year-1900. */
}