Cope with negative C library timestamps

While perhaps not strictly valid, negative timestamps can potentially be
returned by the C library and passed in to iso8601_from_ts() etc. This commit
adds a check for such timestamps and copes with the gracefully, whereas
previously invalid ISO8601 timestamps would have been generated.
This commit is contained in:
Laurence Withers 2010-06-18 12:47:38 +00:00
parent 0d56edd890
commit 944331702f
1 changed files with 14 additions and 1 deletions

View File

@ -22,7 +22,8 @@ iso8601_now(struct iso8601_date* date, struct iso8601_details* details)
if(use_gettimeofday || clock_gettime(CLOCK_REALTIME, &ts)) { if(use_gettimeofday || clock_gettime(CLOCK_REALTIME, &ts)) {
use_gettimeofday = 1; use_gettimeofday = 1;
gettimeofday(&tv, 0); gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec; if(tv.tv_sec < 0) ts.tv_sec = 0;
else ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000L; ts.tv_nsec = tv.tv_usec * 1000L;
} }
@ -79,6 +80,10 @@ iso8601_from_ts(struct iso8601_date* date, const struct timespec* ts)
ldiv_t qr; ldiv_t qr;
qr = ldiv(ts->tv_sec, 86400); qr = ldiv(ts->tv_sec, 86400);
if(ts->tv_sec < 0) {
--qr.quot;
qr.rem += 86400;
}
date->day = EPOCH_GDAY + qr.quot; date->day = EPOCH_GDAY + qr.quot;
date->sec = qr.rem; date->sec = qr.rem;
date->nsec = ts->tv_nsec; date->nsec = ts->tv_nsec;
@ -101,6 +106,10 @@ iso8601_from_tv(struct iso8601_date* date, const struct timeval* tv)
ldiv_t qr; ldiv_t qr;
qr = ldiv(tv->tv_sec, 86400); qr = ldiv(tv->tv_sec, 86400);
if(tv->tv_sec < 0) {
--qr.quot;
qr.rem += 86400;
}
date->day = EPOCH_GDAY + qr.quot; date->day = EPOCH_GDAY + qr.quot;
date->sec = qr.rem; date->sec = qr.rem;
date->nsec = tv->tv_usec * 1000; date->nsec = tv->tv_usec * 1000;
@ -123,6 +132,10 @@ iso8601_from_time_t(struct iso8601_date* date, const time_t* t)
ldiv_t qr; ldiv_t qr;
qr = ldiv(*t, 86400); qr = ldiv(*t, 86400);
if(*t < 0) {
--qr.quot;
qr.rem += 86400;
}
date->day = EPOCH_GDAY + qr.quot; date->day = EPOCH_GDAY + qr.quot;
date->sec = qr.rem; date->sec = qr.rem;
date->nsec = 0; date->nsec = 0;