很多时候,都需要获取Linux的系统时间,每次都是在网上去抄别人的,用完之后就往了。这次做个记录,方便自己以后查阅。
直接上代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
/*
* 获取系统时间,这种方式获取得到的格式是: Wed Mar 30 20:41:21 2022
*/
int printf_time(void)
{
time_t timep;
time(&timep);
char *s = ctime(&timep);
printf("date:%s",s);
return 0;
}
/*
* 获取系统时间,这种方式获取得到的格式是: 2022-03-30 20:41:21.104
*/
int get_time_ms(char *buff, int len)
{
struct timeval tv;
struct tm* ptm;
char time_string[40];
long milliseconds;
if(buff == NULL)
{
printf("%s buff is NULL.\n", __func__);
return -1;
}
gettimeofday(&tv, NULL);
ptm = localtime (&(tv.tv_sec));
strftime (time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); //输出格式为: 2022-03-30 20:38:37
milliseconds = tv.tv_usec / 1000;
snprintf (buff, len, "%s.%03ld", time_string, milliseconds); //输出格式为: 2022-03-30 20:38:37.182
return 0;
}
int main(int argc, const char **argv)
{
char buff[40];
get_time_ms(buff, sizeof(buff));
printf("time:%s\n", buff);
printf_time();
return 0;
}
上程序运行结果:
time:2022-03-30 20:42:21.558
date:Wed Mar 30 20:42:21 2022
更多推荐
Linux 获取系统时间
发布评论