strftime, localtime_r(替代localtime), gettimeofday(替代ftime)

一、

       size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

       The strftime() function returns the number of characters placed in  the
       array  s, not including the terminating null byte, provided the string,
       including the terminating null byte, fits.  Otherwise,  it  returns  0,
       and  the contents of the array is undefined. 

       把tm转换为字符串,存于s。如strftime(format_time, 100 - 2, "%F %T", time_ptr);

  •        %F     Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
  •        %T     The time in 24-hour notation (%H:%M:%S). (SU)


strptime -------- 将字符串按时间格式转换。命令行输入的检查会用到

二、transform date and time to broken-down time or ASCII

       char *asctime(const struct tm *tm);
       char *asctime_r(const struct tm *tm, char *buf);
       char *ctime(const time_t *timep);
       char *ctime_r(const time_t *timep, char *buf);
       struct tm *gmtime(const time_t *timep);
       struct tm *gmtime_r(const time_t *timep, struct tm *result);
       struct tm *localtime(const time_t *timep);
       struct tm *localtime_r(const time_t *timep, struct tm *result);
       time_t mktime(struct tm *tm);

asctime(), ctime(), gmtime() and localtime()返回指针指向静态数据,因此不是线程安全的。

线程安全版本为time_r(), ctime_r(), gmtime_r() and localtime_r()are specified by SUSv2, and available since libc 5.2.5.

三、

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

  • ftime 已经被淘汰了。
  • 秒级,使用time;
  • 毫秒级,使用gettimeofday;
  • 微秒级,使用lock_gettime,但使用不广泛。


举例:

    struct timeval tv;
    gettimeofday(&tv, NULL);
    time_t currentTime = tv.tv_sec;   

    struct tm CurlocalTime;
    localtime_r(&currentTime, &CurlocalTime);
    
    char dateTime[20];
    strftime(dateTime, 20, "%Y-%m-%dT%H:%M:%S", CurlocalTime);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值