2626#include "timelib.h"
2727#include "timelib_private.h"
2828
29- void timelib_unixtime2date (timelib_sll ts , timelib_sll * y , timelib_sll * m , timelib_sll * d )
29+ /* Converts Unix epoch days (days since 1970-01-01) to a date. Algorithm from:
30+ * http://howardhinnant.github.io/date_algorithms.html#civil_from_days */
31+ void timelib_date_from_epoch_days (timelib_sll epoch_days , timelib_sll * y , timelib_sll * m , timelib_sll * d )
3032{
31- timelib_sll days , era , t ;
33+ timelib_sll days , era ;
3234 timelib_ull day_of_era , year_of_era , day_of_year , month_portion ;
3335
3436 /* Calculate days since algorithm's epoch (0000-03-01) */
35- days = ts / SECS_PER_DAY + HINNANT_EPOCH_SHIFT ;
36-
37- /* Adjustment for a negative time portion */
38- t = ts % SECS_PER_DAY ;
39- days += (t < 0 ) ? -1 : 0 ;
37+ days = epoch_days + HINNANT_EPOCH_SHIFT ;
4038
41- /* Calculate year, month, and day. Algorithm from:
42- * http://howardhinnant.github.io/date_algorithms.html#civil_from_days */
4339 era = (days >= 0 ? days : days - DAYS_PER_ERA + 1 ) / DAYS_PER_ERA ;
4440 day_of_era = days - era * DAYS_PER_ERA ;
4541 year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096 ) / DAYS_PER_YEAR ;
@@ -49,6 +45,19 @@ void timelib_unixtime2date(timelib_sll ts, timelib_sll *y, timelib_sll *m, timel
4945 * d = day_of_year - (153 * month_portion + 2 ) / 5 + 1 ;
5046 * m = month_portion + (month_portion < 10 ? 3 : -9 );
5147 * y += (* m <= 2 );
48+ }
49+
50+ void timelib_unixtime2date (timelib_sll ts , timelib_sll * y , timelib_sll * m , timelib_sll * d )
51+ {
52+ timelib_sll epoch_days , t ;
53+
54+ epoch_days = ts / SECS_PER_DAY ;
55+
56+ /* Adjustment for a negative time portion */
57+ t = ts % SECS_PER_DAY ;
58+ epoch_days += (t < 0 ) ? -1 : 0 ;
59+
60+ timelib_date_from_epoch_days (epoch_days , y , m , d );
5261
5362 TIMELIB_DEBUG (printf ("A: ts=%lld, year=%lld, month=%lld, day=%lld," , ts , * y , * m , * d ););
5463}
0 commit comments