Clean up C library functions. Add fallback to gettimeofday() if clock_gettime() fails.

This commit is contained in:
Laurence Withers 2007-07-23 14:40:20 +00:00
parent 47f35dc992
commit a0bc1e3d06
2 changed files with 60 additions and 5 deletions

View File

@ -1,4 +1,4 @@
/* libiso8601/src/libiso8601/c_library.c
/* libiso8601/src/libiso8601/400_c_library.c
*
* (c)2006, Laurence Withers, <l@lwithers.me.uk>.
* Released under the GNU GPLv2. See file COPYING or
@ -12,23 +12,31 @@
void iso8601_now(struct iso8601_date* date, struct iso8601_details* details)
{
static int use_gettimeofday = 0;
struct timespec ts;
struct timeval tv;
struct tm tm;
clock_gettime(CLOCK_REALTIME, &ts);
/* not all systems have clock_gettime implemented */
if(use_gettimeofday || clock_gettime(CLOCK_REALTIME, &ts)) {
use_gettimeofday = 1;
gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000L;
}
// populate the `struct iso8601_date' if it was passed
/* populate the `struct iso8601_date' if it was passed */
if(date) {
iso8601_from_ts(date, &ts);
}
// populate the `struct iso8601_details' if it was passed
/* populate the `struct iso8601_details' if it was passed */
if(details) {
memset(details, 0, sizeof(struct iso8601_details));
details->date_prec = iso8601_prec_day;
details->time_prec = iso8601_prec_secfrac;
// this is silly, but it's the only way to recover the timezone
/* this is silly, but it's the only way to recover the timezone */
localtime_r(&ts.tv_sec, &tm);
details->tz_sec = tm.tm_gmtoff;
}

View File

@ -0,0 +1,47 @@
/* libiso8601/src/libiso8601/400_c_library.h
*
* (c)2006, Laurence Withers, <l@lwithers.me.uk>.
* Released under the GNU GPLv2. See file COPYING or
* http://www.gnu.org/copyleft/gpl.html for details.
*/
/*! \defgroup c_library C library integration.
These functions enable integration with the C library (system call wrappers and conversion).
*/
/*!@{*/
/*! \brief Retrieve the current time.
\param[out] date Current date/time (may be 0), in UTC.
\param[out] details Details (may be 0), including timezone.
Retrieves the current time from the system clock, storing it into \a date and \a details (both
parameters optional).
*/
void iso8601_now(struct iso8601_date* date, struct iso8601_details* details);
/*! \brief Convert from a struct timespec. */
void iso8601_from_ts(struct iso8601_date* date, const struct timespec* ts);
/*! \brief Convert to a struct timespec. */
void iso8601_to_ts(struct timespec* ts, const struct iso8601_date* date);
/*! \brief Convert from a time_t. */
void iso8601_from_time_t(struct iso8601_date* date, const time_t* t);
/*! \brief Convert to a time_t. */
void iso8601_to_time_t(time_t* t, const struct iso8601_date* date);
/*!@}*/
/* options for text editors
kate: replace-trailing-space-save true; space-indent true; tab-width 4;
vim: expandtab:ts=4:sw=4
*/