c-ipfs/util/time.c

39 lines
806 B
C
Raw Permalink Normal View History

2016-12-14 01:16:51 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ipfs/util/time.h"
int ipfs_util_time_parse_RFC3339 (struct timespec *ts, char *s)
2016-12-14 01:16:51 +00:00
{
char *r;
struct tm tm;
if (!ts || !s || strlen(s) != 35) {
2016-12-14 01:16:51 +00:00
return 1;
}
r = strptime (s, "%Y-%m-%dT%H:%M:%S", &tm);
if (!r || *r != '.') {
return 2;
}
ts->tv_sec = mktime(&tm);
ts->tv_nsec = atoll(++r);
2016-12-14 01:16:51 +00:00
return 0;
}
char *ipfs_util_time_format_RFC3339 (struct timespec *ts)
2016-12-14 01:16:51 +00:00
{
char buf[31], *ret;
ret = malloc(36);
if (!ret) {
return NULL;
}
if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.%%09dZ00:00", gmtime(&(ts->tv_sec))) != sizeof(buf)-1 ||
snprintf(ret, 36, buf, ts->tv_nsec) != 35) {
2016-12-14 01:16:51 +00:00
free (ret);
return NULL;
}
return ret;
}