函式
<ctime>

time

time_t time (time_t* timer);
獲取當前時間
獲取當前日曆時間,型別為 time_t

該函式返回此值,如果引數不是空指標,則還會將此值設定為 timer 指向的物件。

返回的值通常表示自 1970 年 1 月 1 日 UTC 00:00:00 以來經過的秒數(即當前的unix時間戳)。雖然庫可能使用不同的時間表示:可移植的程式不應直接使用此函式返回的值,而應始終依賴對標準庫其他元素的呼叫將其轉換為可移植型別(例如 localtimegmtimedifftime)。

引數

timer
指向 time_t 型別物件的指標,時間值儲存在此。
或者,此引數可以是一個空指標,在這種情況下,該引數不被使用(函式仍然返回一個 time_t 型別的值作為結果)。

返回值

作為 time_t 物件的當前日曆時間。

如果引數不是空指標,則返回值與 timer 引數指向的位置中儲存的值相同。

如果函式無法檢索日曆時間,則返回值為 -1

time_t 是一個基本的算術型別的別名,能夠表示時間。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* time example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */

int main ()
{
  time_t timer;
  struct tm y2k = {0};
  double seconds;

  y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
  y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;

  time(&timer);  /* get current time; same as: timer = time(NULL)  */

  seconds = difftime(timer,mktime(&y2k));

  printf ("%.f seconds since January 1, 2000 in the current timezone", seconds);

  return 0;
}

可能的輸出
414086872 seconds since January 1, 2000 in the current timezone


資料競爭

timer 指向的物件將被修改(如果不是的)。

異常 (C++)

無異常保證:此函式從不丟擲異常。

另見