Skip to content

Instantly share code, notes, and snippets.

@andreas-wilm
Created February 3, 2015 06:25
Show Gist options
  • Save andreas-wilm/c72385e96436213dc157 to your computer and use it in GitHub Desktop.
Save andreas-wilm/c72385e96436213dc157 to your computer and use it in GitHub Desktop.
Return ISO 8601 timestamp
/* -*- c-file-style: "k&r"; indent-tabs-mode: nil; -*- */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* returns a timestamp in the form of YYYY-mm-dd HH-MM.
* buf needs to be able to hold 19+1 characters (incl. \0).
* returns 0 on success -1 otherwise.
*/
int timestamp(char *buf)
{
time_t ltime;
struct tm *tm;
buf[0] = '\0'; /* avoid undefined results */
if (time(&ltime) == (time_t)-1) {
return -1;
}
if ((tm = localtime(&ltime))==NULL) {
return -1;
}
if (strftime(buf, 20, "%Y-%m-%dT%H:%M:%S", tm) != 19) {
buf[0] = '\0'; /* avoid undefined results */
return -1;
}
return 0;
}
int main(void)
{
char buf[20];
if (timestamp(buf) == 0) {
printf("%s\n", buf);
} else {
printf("timestamp() failed\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment