Skip to content

Instantly share code, notes, and snippets.

@leiless
Last active June 13, 2020 02:32
Show Gist options
  • Save leiless/cc175fb023f58a188500614c8735b4e1 to your computer and use it in GitHub Desktop.
Save leiless/cc175fb023f58a188500614c8735b4e1 to your computer and use it in GitHub Desktop.
Format usual time string
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#define TIMESTR_SZ 32
static const char *timestr(void)
{
static char str[TIMESTR_SZ];
struct timeval tv;
struct tm *t;
(void) gettimeofday(&tv, NULL); /* Won't fail */
t = localtime(&tv.tv_sec);
*str = '\0';
if (t != NULL) {
(void)
snprintf(str, sizeof(str), "%2d/%02d/%02d %02d:%02d:%02d.%03ld +%04ld",
(1900 + t->tm_year) % 100, t->tm_mon + 1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec / 1000, t->tm_gmtoff * 100 / 3600);
}
return str;
}
int main(void)
{
printf("%s\n", timestr());
return 0;
}
@leiless
Copy link
Author

leiless commented Jun 13, 2020

Safe implementation timestr():

/*
 * Created Jun 13, 2020.
 */

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>

#define TIMESTR_BUFSZ       32

/**
 * Format current time into human-readable string
 * @return      NULL if OOM, you're responsible to free(3) the buffer.
 */
char *timestr(void)
{
    char s[TIMESTR_BUFSZ];
    struct timeval tv;
    struct tm t;

    (void) gettimeofday(&tv, NULL);     /* Won't fail */
    (void) localtime_r(&tv.tv_sec, &t);
    (void) snprintf(s, sizeof(s), "%2d/%02d/%02d %02d:%02d:%02d.%03ld +%04ld",
                     (1900 + t.tm_year) % 100, t.tm_mon + 1, t.tm_mday,
                     t.tm_hour, t.tm_min, t.tm_sec,
                     tv.tv_usec / 1000, t.tm_gmtoff * 100 / 3600);

    return strdup(s);
}

int main(void)
{
    char *t = timestr();
    printf("%s\n", t);
    free(t);
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment