跳到主要内容

C++ time() 函数

C++ 中的 time() 函数返回当前日历时间,其类型为 time_t 对象。该函数定义在 ctime 头文件中。

示例

#include <iostream>
#include <ctime>
using namespace std;

int main() {

// 使用带 NULL 参数的 time()
cout << time(NULL);

return 0;
}

// 输出:1629799688

time() 语法

time() 函数的语法为:

time(time_t* arg);

time() 参数

time() 函数接受以下参数:

  • arg:指向 time_t 对象的指针,如果非 NULL 则存储时间。

time() 返回值

time() 函数返回:

  • 成功时 - 当前日历时间,类型为 time_t
  • 失败时 - 返回 -1,并被转换为 time_t 类型。

time() 原型

ctime 头文件中定义的 time() 原型为:

time_t time(time_t* arg);

示例 1:C++ time()

#include <iostream>
#include <ctime>
using namespace std;

int main() {
time_t current_time;

current_time = time(NULL);

cout << current_time;
cout << " 秒已经过去,自 1970 年 1 月 1 日 00:00:00 GMT";

return 0;
}

输出

1629810340 秒已经过去,自 19701100:00:00 GMT

示例 2:C++ time() 使用引用指针

#include <iostream>
#include <ctime>
using namespace std;

int main() {
time_t current_time;

// 在 current_time 中存储时间
time(&current_time);

cout << current_time;
cout << " 秒已经过去,自 1970 年 1 月 1 日 00:00:00 GMT";

return 0;
}

输出

1629810340 秒已经过去,自 19701100:00:00 GMT