Last active
June 13, 2020 02:32
-
-
Save leiless/cc175fb023f58a188500614c8735b4e1 to your computer and use it in GitHub Desktop.
Format usual time string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Safe implementation
timestr():