From ad5ce55281a3f3e9fc6edfe93a759d2622a45c0f Mon Sep 17 00:00:00 2001 From: leitner Date: Wed, 13 May 2015 20:33:51 +0000 Subject: [PATCH] add fmt_iso8601 --- fmt.h | 3 +++ fmt/fmt_iso8601.c | 31 +++++++++++++++++++++++++++++++ test/fmt_iso8691.c | 10 ++++++++++ 3 files changed, 44 insertions(+) create mode 100644 fmt/fmt_iso8601.c create mode 100644 test/fmt_iso8691.c diff --git a/fmt.h b/fmt.h index 94591a8..2a17a6c 100644 --- a/fmt.h +++ b/fmt.h @@ -137,6 +137,9 @@ size_t fmt_humank(char* dest,unsigned long long l); /* "Sun, 06 Nov 1994 08:49:37 GMT" */ size_t fmt_httpdate(char* dest,time_t t); +/* "2014-05-27T19:22:16.247Z" */ +size_t fmt_iso8601(char* dest,time_t t); + #define FMT_UTF8 5 #define FMT_ASN1LENGTH 17 /* enough space to hold 2^128-1 */ #define FMT_ASN1TAG 19 /* enough space to hold 2^128-1 */ diff --git a/fmt/fmt_iso8601.c b/fmt/fmt_iso8601.c new file mode 100644 index 0000000..f379325 --- /dev/null +++ b/fmt/fmt_iso8601.c @@ -0,0 +1,31 @@ +#include "fmt.h" +#include "byte.h" +#include + +static unsigned int fmt_2digits(char* dest,int i) { + dest[0]=(char)((i/10)+'0'); + dest[1]=(char)((i%10)+'0'); + return 2; +} + +size_t fmt_iso8601(char* dest,time_t t) { + struct tm* x=gmtime(&t); + size_t i; + + if (dest==0) return sizeof("2014-05-27T19:22:16Z")-1; + /* "2014-05-27T19:22:16Z" */ + i=fmt_2digits(dest,(x->tm_year+1900)/100); + i+=fmt_2digits(dest+i,(x->tm_year+1900)%100); + dest[i++]='-'; + i+=fmt_2digits(dest+i,x->tm_mon+1); + dest[i++]='-'; + i+=fmt_2digits(dest+i,x->tm_mday); + dest[i++]='T'; + i+=fmt_2digits(dest+i,x->tm_hour); + i+=fmt_str(dest+i,":"); + i+=fmt_2digits(dest+i,x->tm_min); + i+=fmt_str(dest+i,":"); + i+=fmt_2digits(dest+i,x->tm_sec); + i+=fmt_str(dest+i,"Z"); + return i; +} diff --git a/test/fmt_iso8691.c b/test/fmt_iso8691.c new file mode 100644 index 0000000..44765b3 --- /dev/null +++ b/test/fmt_iso8691.c @@ -0,0 +1,10 @@ +#include +#include +#include + +int main() { + char buf[1024]; + write(1,buf,fmt_iso8601(buf,0)); + write(1,"\n",1); + return 0; +}