[c/c++][Linux] 时间类型操作汇总笔记

6 篇文章 0 订阅

目录

Linux下获取微秒级时间


ref:
(郝峰波) https://www.cnblogs.com/fengbohello/p/4153831.html


定义

#include <sys/time.h>
int gettimeofday(struct timeval*tv, struct timezone *tz);

其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果(此处不需要tz,故使用时将其置为NULL即可)
struct timeval定义如下

struct timeval{
	long int tv_sec; // 秒数
	long int tv_usec; // 微秒数
}

示例

#include <stdio.h>        // for printf()
#include <sys/time.h>     // for gettimeofday()
#include <unistd.h>       // for sleep()

int main()
{
    struct timeval start, end;
    gettimeofday( &start, NULL );
    printf("start : %d.%d\n", start.tv_sec, start.tv_usec);
    sleep(1);
    gettimeofday( &end, NULL );
    printf("end   : %.6lf\n", end.tv_sec + end.tv_usec * 0.000001);

    return 0;
}

输出

start : 1571211587.119612
end   : 1571211588.119762

time_t和struct tm之间的转换


ref:
版权声明:本文为CSDN博主「fulinux」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fulinus/article/details/40083295


time_t到struct tm的转换:

#include <time.h>
struct tm *localtime(const time_t *timep);

struct tm到time_t的转换:

#include <time.h>
time_t mktime(struct tm *tm);

strptime时间字符串格式化为struct tm


ref:https://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html


定义

char *strptime(const char *restrict buf, const char *restrict format,
       struct tm *restrict tm);

示例

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

int main()
{

    char time[100] = "2019-10-16 16:00:00";
    char time_format[100] = "%Y-%m-%d %H:%M:%S";

    struct tm tm;
    strptime(time, time_format, &tm);

    printf("Time is %04d-%02d-%02d %02d:%02d:%02d\n", 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);

    return 0;
}

输出

Time is 2019-10-16 16:00:00
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值