linux系統時間程式設計(8) UTC秒數轉本地字串時間

奇妙之二進位制發表於2021-01-02
<time.h>
char* ctime ( const time_t* timer );(1)
char* ctime_r( const time_t* timer, char* buf );(2)(since C23)
errno_t ctime_s( char buf, rsize_t bufsz, const time_t timer );(3)(since C11)

該函式執行了兩步操作,相當於:
asctime(localtime(timer)) or asctime(localtime_r(timer, &(struct tm){0}))

返回的字串格式:
Www Mmm dd hh:mm:ss yyyy\n

  • Www - the day of the week (one of Mon, Tue, Wed, Thu, Fri, Sat, Sun).
  • Mmm - the month (one of Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
  • dd - the day of the month
  • hh - hours
  • mm - minutes
  • ss - seconds
  • yyyy - years

同樣執行緒不安全。

#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
#include <stdio.h>
 
int main(void)
{
    time_t result = time(NULL);
    printf("%s", ctime(&result));
 
#ifdef __STDC_LIB_EXT1__
    char str[26];
    ctime_s(str,sizeof str,&result);
    printf("%s", str);
#endif
}

Possible output:

Tue May 26 21:51:03 2015
Tue May 26 21:51:03 2015

相關文章