linux下time转换

linux 几种时间格式

//底精度

time_t tv_sec; // seconds

typedef struct timespec timespec_t;
struct timespec {
time_t tv_sec; // seconds time_t就是long int 类型
long tv_nsec; // and nanoseconds
};

//高精度

struct timeval us; //gettimeofday(&us,NULL);
timespec time; //
struct tm now_time; //

//时间获取
time_t time(NULL); // 等同于now = time(NULL) //获取相对于1970到现在的秒数
stat(filename->d_name, &file_stat); //获取相对于1970到现在的秒数
clock_gettime(CLOCK_REALTIME, &time); //获取相对于1970到现在的秒数

//以下为time_t转换为本地时间

time_t -> tm
localtime_r(&file_stat.st_atime, &now_time);

timespec -> tm
localtime_r(&time.tv_sec, &nowtime);

time_t -> tm
struct tm *tblock = localtime(&timer);

tm -> string
方法1
struct tm *nowtime = localtime(&timer);
sprintf(date_time, “%d-%d-%d %d:%d:%d\n”, now_time->tm_year + 1900, now_time->tm_mon + 1,
now_time->tm_mday, now_time->tm_hour, now_time->tm_min, now_time->tm_sec);
方法2
struct tm now_time; //
localtime_r(&time.tv_sec, &nowtime);
strftime(date_time, sizeof(date_time), “%Y-%m-%d %H:%M:%S”, localtime_r(&file_stat.st_mtime, &t));

方法3
struct tm now_time;     //
localtime_r(&file_stat.st_atime, &now_time);
sprintf(date_time, "%d-%d-%d %d:%d:%d\n", now_time.tm_year + 1900, now_time.tm_mon + 1,
                now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);

timeval -> string
printf(“gettimeofday: tv_sec=%ld, tv_usec=%ld\n”, us.tv_sec, us.tv_usec);

time_t -> string

高精度
gettimeofday

struct timeval tv;
struct timezone tz;
gettimeofday (&tv , &tz);
printf(“tv_sec; %d\n”, tv,.tv_sec);
printf(“tv_usec; %d\n”,tv.tv_usec);
printf(“tz_minuteswest; %d\n”, tz.tz_minuteswest);
printf(“tz_dsttime, %d\n”,tz.tz_dsttime);


linux下time转换
http://blog.uanet.cn/SYSTEM/linux下time转换.html
作者
dnsnat
发布于
2022年5月9日
许可协议