获取当前时间字符串的方法
#include <stdio.h>
#include <string.h>
#include <time.h>
static void get_format_time_string(time_t time, char* format, char *buf)
{
if (buf == NULL) {
return;
}
struct tm mytm={0};
struct tm* p_tm = localtime_r(&time,&mytm);
if (p_tm == NULL) {
return;
}
sprintf(buf, format, p_tm->tm_hour, p_tm->tm_min, p_tm->tm_sec, p_tm->tm_mon + 1, p_tm->tm_mday, p_tm->tm_year + 1900);
}
static void get_compact_time_string(time_t time, char* buf) {
get_format_time_string(time, "%02d:%02d:%02d %02d-%02d-%4d", buf);
}
测试用例
int main()
{
char time_buf[15]={0};
get_compact_time_string(time(NULL), time_buf);
printf("time_string=%s\n", time_buf);
return 0;
}
运行结果
$ gcc time_demo.c -o time
$ ./time
time string=18:50:22 01-27-2022