Linux C语言获取系统年-月-日,时-分-秒,精确到毫秒

我们知道,通过下面gettimeofday函数的方法获得的是系统的时间戳

struct timeval tv;
gettimeofday(&tv,NULL);
int64_t time = tv.tv_sec*1000 + tv.tv_usec/1000;

那么如何获取到年月日,时分秒,并且精确到毫秒呢?

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

void main()
{
    struct timeval tv;
    struct timezone tz;   
    struct tm *t;
     
    gettimeofday(&tv, &tz);
    t = localtime(&tv.tv_sec);
    printf("%d-%d-%d %d:%d:%d.%ld\n", 1900+t->tm_year, 1+t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec);
}

输出结果:

2022-1-19 3:51:8.835209

struct tm的定义:

struct tm
{
    int tm_sec; /*秒,正常范围0-59, 但允许至61*/
    int tm_min; /*分钟,0-59*/
    int tm_hour; /*小时, 0-23*/
    int tm_mday; /*日,即一个月中的第几天,1-31*/
    int tm_mon; /*月, 从一月算起,0-11*/ 1+p->tm_mon;
    int tm_year; /*年, 从1900至今已经多少年*/ 1900+ p->tm_year;
    int tm_wday; /*星期,一周中的第几天, 从星期日算起,0-6*/
    int tm_yday; /*从今年1月1日到目前的天数,范围0-365*/
    int tm_isdst; /*日光节约时间的旗标*/
};

这个结构体是系统定义好的,不需要自己定义

  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值