unix下时间相关的函数

表示时间的数据结构

表示时间戳:time_t

表示年月日时分秒:struct tm

struct tm {
  int tm_sec;     /* 秒,范围从 0 到 59        */
  int tm_min;     /* 分,范围从 0 到 59        */
  int tm_hour;    /* 小时,范围从 0 到 23        */
  int tm_mday;    /* 一月中的第几天,范围从 1 到 31   */
  int tm_mon;     /* 月份,范围从 0 到 11        */
  int tm_year;    /* 自 1900 起的年数        */
  int tm_wday;    /* 一周中的第几天,范围从 0 到 6  */
  int tm_yday;    /* 一年中的第几天,范围从 0 到 365 */
  int tm_isdst;    /* 夏令时            */
};

表示秒+纳秒:struct timespec

struct timespec
{
    __time_t tv_sec;            /* Seconds.  */
    __syscall_slong_t tv_nsec;  /* Nanoseconds.  */
};

表示秒+微秒:struct timeval

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

表示时区:struct timezone

struct  timezone{
        int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
        int tz_dsttime;/*type of DST correction*/
}

获取时间

获取秒级别的时间戳:time

time函数返回1970-01-01 00:00:00 +0000时刻以来的秒数。

#include <time.h>
time_t time(time_t *t);
返回值:正常返回时间戳,同时t指针指向这个时间戳

获取微秒级别的时间戳:gettimeofday

这个函数的作用是获取当前时刻对应的时间戳和时区,时间戳是相对1970年以来的秒+微秒数。

#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
返回值:执行成功,返回0,执行失败返回-1,并且置上errno
tv:指向获取到的时间,如果仅获取时区,那么tv可以传NULL;
tz:指向获取到的时区,如果仅获取时间戳,那么tz可以传NULL;

获取年月日时分秒:localtime

struct tm *localtime(const time_t *t);//传入秒数,返回年月日时分秒

获取格式化后的时间:strftime

#include <time.h>
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
返回值:成功的话返回格式化后的时间字符串大小,失败返回0;
s:用于记录格式化后的时间字符串的缓存;
max:缓存大小;
format:格式,比如:"Now is %Y/%m/%d %H:%M:%S";
tm:待转换的时间

举例

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

int
main(int argc, char **argv)
{
        time_t time1;
        struct tm *time2;
        char buff[1024];
        time(&time1);
        time2 = localtime(&time1);
        if (strftime(buff, sizeof(buff), "Now is %Y/%m/%d %H:%M:%S", time2)) {
                printf("time: %s\n", buff);
        }
        else {
                perror("strftime failed.\n");
                return -1;
        }
        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值