C庫 - ctime() 函式



C庫的`ctime()`函式返回一個字串,該字串表示基於引數timer的本地時間。它將時鐘表示的時間(自紀元以來的秒數)轉換為本地時間字串格式。

返回的字串具有以下格式:Www Mmm dd hh:mm:ss yyyy,其中Www是星期幾,Mmm是月份的字母縮寫,dd是月份中的日期,hh:mm:ss是時間,yyyy是年份。

語法

以下是C庫`ctime()`函式的語法:

char *ctime(const time_t *timer)

引數

此函式只接受一個引數:

  • timer - 這是指向包含日曆時間的time_t物件的指標。

返回值

此函式返回一個C字串,其中包含以人類可讀格式表示的日期和時間資訊。

示例1

以下是一個基本的C庫程式,演示`ctime()`函式的使用。

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

int main () {
   time_t curtime;

   time(&curtime);

   printf("Current time = %s", ctime(&curtime));

   return(0);
}

輸出

執行上述程式碼後,我們將得到以下結果:

Current time = Mon Aug 13 08:23:14 2012

示例2

在列印日期和時間時,它使用time()函式檢索當前系統時間(自紀元以來的秒數),並使用ctime()函式將時間轉換為字串格式。

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

int main() {
   // Current date/time
   time_t tm = time(NULL);
   // convert into string
   char* st = ctime(&tm);
   printf("Date/Time: %s", st);
   return 0;
}

輸出

執行程式碼後,我們將得到以下結果:

Date/Time: Tue May 14 06:50:22 2024

示例3

下面的C示例使用time()函式計算從現在起一小時後的本地時間,並使用ctime()函式以人類可讀的格式顯示它。

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

int main() {
   // Create a time_t object representing 1 hour from now
   time_t one_hour_from_now = time(NULL) + 3600;

   // Convert one_hour_from_now to string form
   char* dt = ctime(&one_hour_from_now);

   // Print the date and time
   printf("One hour from now, the date and time will be: %s\n", dt);
   return 0;
}

輸出

上述程式碼產生以下結果:

One hour from now, the date and time will be: Tue May 14 07:23:22 2024
廣告