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);


你可能感兴趣的:(strftime, localtime_r(替代localtime), gettimeofday(替代ftime))