From 944331702f7bbb2ff3f77109b617864dad0d1b8c Mon Sep 17 00:00:00 2001 From: Laurence Withers Date: Fri, 18 Jun 2010 12:47:38 +0000 Subject: [PATCH] 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. --- src/libiso8601/400_c_library.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/libiso8601/400_c_library.c b/src/libiso8601/400_c_library.c index 0d810af..effd788 100644 --- a/src/libiso8601/400_c_library.c +++ b/src/libiso8601/400_c_library.c @@ -22,7 +22,8 @@ iso8601_now(struct iso8601_date* date, struct iso8601_details* details) if(use_gettimeofday || clock_gettime(CLOCK_REALTIME, &ts)) { use_gettimeofday = 1; 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; } @@ -79,6 +80,10 @@ iso8601_from_ts(struct iso8601_date* date, const struct timespec* ts) ldiv_t qr; qr = ldiv(ts->tv_sec, 86400); + if(ts->tv_sec < 0) { + --qr.quot; + qr.rem += 86400; + } date->day = EPOCH_GDAY + qr.quot; date->sec = qr.rem; date->nsec = ts->tv_nsec; @@ -101,6 +106,10 @@ iso8601_from_tv(struct iso8601_date* date, const struct timeval* tv) ldiv_t qr; qr = ldiv(tv->tv_sec, 86400); + if(tv->tv_sec < 0) { + --qr.quot; + qr.rem += 86400; + } date->day = EPOCH_GDAY + qr.quot; date->sec = qr.rem; 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; qr = ldiv(*t, 86400); + if(*t < 0) { + --qr.quot; + qr.rem += 86400; + } date->day = EPOCH_GDAY + qr.quot; date->sec = qr.rem; date->nsec = 0;