fix(core): Simplify time conversion and fix an edge case for negative dates

This commit is contained in:
Julius Pfrommer 2019-08-31 17:30:52 +02:00 committed by Stefan Profanter
parent c455ed1e67
commit 055b1a0484
2 changed files with 10 additions and 35 deletions

33
deps/libc_time.c vendored
View File

@ -16,7 +16,6 @@ int __secs_to_tm(long long t, struct mytm *tm) {
int remdays, remsecs, remyears;
int qc_cycles, c_cycles, q_cycles;
int months;
int wday, yday, leap;
static const char days_in_month[] = {31,30,31,30,31,31,30,31,30,31,31,29};
/* Reject time_t values whose year would overflow int */
@ -31,9 +30,6 @@ int __secs_to_tm(long long t, struct mytm *tm) {
--days;
}
wday = (int)((3+days)%7);
if (wday < 0) wday += 7;
qc_cycles = (int)(days / DAYS_PER_400Y);
remdays = (int)(days % DAYS_PER_400Y);
if (remdays < 0) {
@ -53,10 +49,6 @@ int __secs_to_tm(long long t, struct mytm *tm) {
if (remyears == 4) --remyears;
remdays -= remyears * 365;
leap = !remyears && (q_cycles || !c_cycles);
yday = remdays + 31 + 28 + leap;
if (yday >= 365+leap) yday -= 365+leap;
years = remyears + 4*q_cycles + 100*c_cycles + 400LL*qc_cycles;
for (months=0; days_in_month[months] <= remdays; ++months)
@ -72,9 +64,6 @@ int __secs_to_tm(long long t, struct mytm *tm) {
++tm->tm_year;
}
tm->tm_mday = remdays + 1;
tm->tm_wday = wday;
tm->tm_yday = yday;
tm->tm_hour = remsecs / 3600;
tm->tm_min = remsecs / 60 % 60;
tm->tm_sec = remsecs % 60;
@ -82,42 +71,32 @@ int __secs_to_tm(long long t, struct mytm *tm) {
return 0;
}
int __month_to_secs(int month, int is_leap) {
static const int secs_through_month[] =
{0, 31*86400, 59*86400, 90*86400,
120*86400, 151*86400, 181*86400, 212*86400,
243*86400, 273*86400, 304*86400, 334*86400 };
static int
__month_to_secs(int month, int is_leap) {
int t = secs_through_month[month];
if (is_leap && month >= 2)
t+=86400;
return t;
}
long long __year_to_secs(long long year, int *is_leap) {
if (year-(int)2ULL <= 136) {
long long y = (int)year;
long long leaps = (y-68)>>2;
if (!((y-8)&3)) {
leaps--;
if (is_leap) *is_leap = 1;
} else if (is_leap) *is_leap = 0;
return 31536000*(y-70) + 86400*leaps;
}
static long long
__year_to_secs(const long long year, int *is_leap) {
int cycles, centuries, leaps, rem;
//if (!is_leap) is_leap = &(int){0};
int is_leap_val = 0;
if (!is_leap) {
is_leap = &is_leap_val;
}
cycles = (int)((year-100) / 400);
rem = (int)((year-100) % 400);
/* Comparison is always false because rem >= 0.
if (rem < 0) {
cycles--;
rem += 400;
} */
}
if (!rem) {
*is_leap = 1;
centuries = 0;

4
deps/libc_time.h vendored
View File

@ -8,13 +8,9 @@ struct mytm {
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
};
int __secs_to_tm(long long t, struct mytm *tm);
int __month_to_secs(int month, int is_leap);
long long __year_to_secs(long long year, int *is_leap);
long long __tm_to_secs(const struct mytm *tm);
#endif /* LIBC_TIME_H_ */