用于获取当前时间戳(1970 年以来的秒数),通常用于简单的时间计算,时间精度为秒级。
1.头文件
#include <time.h>
2.函数原型
time_t time(time_t *tloc);
3.参数
tloc: 这是一个指向 time_t 类型的指针,函数会将当前时间的值存储在这个指针所指向的地址中。如果传入 NULL,则该函数只返回当前时间,而不将其存储到任何地方。
4.返回值
函数返回自 1970 年 1 月 1 日 00:00:00 UTC(即 Unix 时间戳)以来的秒数,类型为 time_t。如果发生错误,返回值为 -1。
5.示例:(使用time获取当前时间)
| #include <stdio.h>
#include <time.h> int main() { time_t current_time; // 获取当前时间 current_time = time(NULL); // 或者可以使用 time(¤t_time); // 检查是否获取成功 if (current_time == -1) { perror("time"); return 1; } // 将时间转为字符串格式 printf("Current time in seconds since epoch: %ldn", current_time); // 如果需要将时间存储在 tloc 中 time_t tloc; time(&tloc); printf("Current time stored in tloc: %ldn", tloc); return 0; } |
6.查看测试结果
| Current time in seconds since epoch: 1730945690
Current time stored in tloc: 1730945690 |
216