strftime() 函式在 C/C++ 中


strftime() 函式用於將時間和日期格式化為字串。它在 C 中的“time.h”標頭檔案中宣告。如果字串大小在 size 字元內,則返回複製到字串中的字元總數,否則返回零。

以下是 C 中 strftime() 的語法:

size_t strftime(char *string, size_t size, const char *format, const struct tm *time_pointer)

此中:

string − 指向目標陣列的指標。

size − 要複製的最大字元數。

format − 表示 tm 時間的一些特殊格式說明符。

time_pointer − 指向包含日曆時間結構的 tm 結構的指標。

以下是 C 中 strftime() 的一個示例:

示例

 即時演示

#include <stdio.h>
#include <time.h>
int main () {
   time_t tim;
   struct tm *detl;
   char buf[80];
   time( &tim );
   detl = localtime( &tim );
   strftime(buf, 20, "%x - %I:%M%p", detl);
   printf("Date & time after formatting : %s", buf );
   return(0);
}

輸出

Date & time after formatting : 10/23/18 - 10:33AM

在上面的程式中,聲明瞭多個數據型別的三個變數。函式 localtime() 儲存當前日期和時間。函式 strftime() 正在複製字串,並使用一些特殊說明符以一些特殊結構對其進行格式化。

detl = localtime( &tim );
strftime(buf, 20, "%x - %I:%M%p", detl);

更新時間:2020-6 月 26 日

635 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.