在日常工作中,有时候我们需要对时间做处理,这个时候就要能获取到系统当前时间

而且,关键时候要能精确到毫秒级别!不然精度不够!!!

 

话不多说,代码如下:

 

#include <stdio.h> 
#include <time.h> 
#include <sys/time.h> 
   
void sysLocalTime() 
{ 
    time_t             timesec; 
    struct tm         *p; 
       
       
    time(×ec); 
    p = localtime(×ec); 
       
    printf("%d%d%d%d%d%d\n", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); 
       
} 
   
void sysUsecTime() 
{ 
    struct timeval    tv; 
    struct timezone tz; 
       
    struct tm         *p; 
       
    gettimeofday(&tv, &tz); 
    printf("tv_sec:%ld\n",tv.tv_sec); 
    printf("tv_usec:%ld\n",tv.tv_usec); 
    printf("tz_minuteswest:%d\n",tz.tz_minuteswest); 
    printf("tz_dsttime:%d\n",tz.tz_dsttime); 
       
    p = localtime(&tv.tv_sec); 
    printf("time_now:%d%d%d%d%d%d.%ld\n", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, tv.tv_usec); 
} 
   
int main(void) 
{ 
    sysLocalTime(); 
    printf("============gettimeofday==============\n"); 
       
    sysUsecTime(); 
       
    return 0; 
} 

以上就是C语言写的获取Linux系统当前时间!(精确到毫秒)

 

GitHub 加速计划 / li / linux-dash
6
1
下载
A beautiful web dashboard for Linux
最近提交(Master分支:4 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐