diff mbox series

[09/12] util: add swupdate_time_iso8601

Message ID 20181002143357.9329-9-sbabic@denx.de
State Accepted
Headers show
Series [01/12] channel_curl: allow answers not in JSON format | expand

Commit Message

Stefano Babic Oct. 2, 2018, 2:33 p.m. UTC
Add an accessor to get the local time according to
ISO8601 format.

Signed-off-by: Stefano Babic <sbabic@denx.de>
---
 core/util.c    | 37 +++++++++++++++++++++++++++++++++++++
 include/util.h |  2 ++
 2 files changed, 39 insertions(+)
diff mbox series

Patch

diff --git a/core/util.c b/core/util.c
index bc4a468..15d38b7 100644
--- a/core/util.c
+++ b/core/util.c
@@ -16,9 +16,11 @@ 
 #include <sys/stat.h>
 #include <sys/param.h>
 #include <sys/mount.h>
+#include <sys/time.h>
 #include <sys/uio.h>
 #include <dirent.h>
 #include <limits.h>
+#include <time.h>
 
 #include "swupdate.h"
 #include "util.h"
@@ -566,3 +568,38 @@  int swupdate_umount(const char *dir)
 #endif
 }
 
+/*
+ * Date time in SWUpdate
+ * @return : date in ISO8601 (it must be freed by caller)
+ */
+char *swupdate_time_iso8601(void)
+{
+	#define DATE_SIZE_ISO8601	128
+	struct timeval now;
+	int ms;
+	char msbuf[4];
+	/* date length is fix, reserve enough space */
+	char *buf = (char *)malloc(DATE_SIZE_ISO8601);
+
+	if (!buf)
+		return NULL;
+
+	gettimeofday(&now, NULL);
+	ms = now.tv_usec / 1000;
+
+	(void)strftime(buf, DATE_SIZE_ISO8601, "%Y-%m-%dT%T.***%z", localtime(&now.tv_sec));
+
+	/*
+	 * Replace '*' placeholder with ms value
+	 */
+	snprintf(msbuf, sizeof(msbuf), "%03d", ms);
+	memcpy(strchr(buf, '*'), msbuf, 3);
+
+	/*
+	 * strftime add 4 bytes for timezone, ISO8601 uses
+	 * +hh notation. Drop the last two bytes.
+	 */
+	buf[strlen(buf) - 2] = '\0';
+
+	return buf;
+}
diff --git a/include/util.h b/include/util.h
index 99c37e1..7804ff5 100644
--- a/include/util.h
+++ b/include/util.h
@@ -195,4 +195,6 @@  const char* get_tmpdirscripts(void);
 int swupdate_mount(const char *device, const char *dir, const char *fstype);
 int swupdate_umount(const char *dir);
 
+/* Date / Time utilities */
+char *swupdate_time_iso8601(void);
 #endif