将gettimeofday获取可显示的字符串时间?

https://www.elecfans.com/d/1887419.html
大家在平时的项目中,一定经常面临打日志信息的问题,在打日志这个问题上,大家有时一定会非常关注【时间戳】这个信息点。

想必大家也很经常使用【gettimeofday】接口来获取当前的系统时间,但是很遗憾的是,它获取的时间信息是存储在一个叫strcut timeval的结构体中。那么如何将这个结构体的时间信息转换为可是显示的时间字符串呢?

#include 
#include 
#include 
#include 

//由struct timeval结构体数据(由gettimeofday获取到的)转换成可显示的时间字符串
static char * get_local_time(char *time_str, int len, struct timeval *tv)
{
    struct tm* ptm;
    char time_string[40];
    long milliseconds;
    
    ptm = localtime (&(tv->tv_sec));

    /* 格式化日期和时间,精确到秒为单位。*/
    //strftime (time_string, sizeof(time_string), "%Y/%m/%d %H:%M:%S", ptm); //输出格式为: 2018/12/09 10:48:31.391
    //strftime (time_string, sizeof(time_string), "%Y|%m|%d %H-%M-%S", ptm); //输出格式为: 2018|12|09 10-52-28.302
    //strftime (time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", ptm); //输出格式为: 2018-12-09 10:52:57.200
    strftime (time_string, sizeof(time_string), "%Y\\%m\\%d %H-%M-%S", ptm); //输出格式为: 2018\12\09 10-52-28.302

    /* 从微秒计算毫秒。*/
    milliseconds = tv->tv_usec / 1000;

    /* 以秒为单位打印格式化后的时间日期,小数点后为毫秒。*/
    snprintf (time_str, len, "%s.%03ld", time_string, milliseconds);

    return time_str;
}

int main(int argc, const char **argv)
{
    char local_time_str[128];
    char *p = NULL;
    struct timeval tv;

    gettimeofday(&tv, NULL);
    p = get_local_time(local_time_str, sizeof(local_time_str), &tv);
    printf("Get local time: \n%s\n", p);

    return 0;
}

编译代码,输入:

gcc -o time_string_format time_string_format.c
测试结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值