From 0c12cbedbb1626597acf2f43718c6b52fc42d08a Mon Sep 17 00:00:00 2001 From: antirez Date: Wed, 4 Jul 2018 13:25:55 +0200 Subject: [PATCH] Localtime: compute year, month and day of the month. --- src/localtime.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/localtime.c b/src/localtime.c index a92d7464..d4090e63 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. */ }