C标准库-时间函数

时间函数

time函数

c 复制代码
time_t time(time_t* tloc);

功能:获取自1970-01-01 00:00:00 到当前的秒数

tloc:若传入非空指针,函数会把"秒数"结果写入变量中,若传入NULL函数仅返回秒数,但不写入变量。

返回值:成功返回秒数,失败返回错误码并设置errno

localtime函数

c 复制代码
struct tm* localtime(const time_t* timep)

功能:将time_t的秒数转换为tm结构体

timp:秒钟变量的地址

返回值:成功返回tm结构体,失败返回NULL并设置相应的错误码

tm结构体

c 复制代码
struct tm {
	int tm_sec; //秒(0-60)
	int tm_min; //分(0-59)
	int tm_hour; //小时(0-23)
	int tm_mday; //日(1-31)
	int tm_mon; //月(0-11)
	int tm_year; //年(Year - 1900)
	int tm_wday; //星期(0-6 Sunday=0)
	int tm_yday; //年中的第几天(0-365 1 Jan = 0)
	int tm_isdst; //夏令时
};

实例

c 复制代码
#include <time.h>
#include <stdio.h>

int main(void)
{
	time_t now = time(0);
	struct tm* tstruct = localtime(&now);
	fprintf(stdout,"Current time:%d\n", &now);
	fprintf(stdout,"%04d-%02d-%02d %02d:%02d:%02d\n",
		tstruct->tm_year + 1900, tstruct->tm_mon, tstruct->tm_mday,
		tstruct->tm_hour, tstruct->tm_min, tstruct->tm_sec);

	return 0;
}

运行结果:

相关推荐
Logic1012 小时前
C语言/数据结构位运算题解:异或XOR找出书柜中编号只出现一次的那一层——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Logic1014 小时前
C语言/数据结构位运算题解:异或XOR找出星球探险中的“独特能量石“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Escalating_xu5 小时前
【C 语言】深入理解指针(3):字符指针、数组指针、二维数组传参、函数指针与转移表
java·c语言·开发语言
垆边人似月.5 小时前
华为机考题:最小代价爬楼梯
c语言·c++
垆边人似月.6 小时前
华为机考题:二叉树的最大路径和
c语言·c++
程序猿编码6 小时前
不用 PyTorch!纯 C 实现 N 维张量 + 反向传播,完成手写数字识别训练
c语言·人工智能·pytorch·神经网络·卷积神经网络·大模型推理
Navigator_Z7 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
垆边人似月.8 小时前
华为机考题:矩阵中的最长递增路径
c语言·c++
free-elcmacom9 小时前
手撕 memcpy 和 memmove:从字节级拷贝到内存重叠的终极较量
c语言·开发语言·青少年编程·visual studio code·visual studio
程序员_小兵9 小时前
PCIe Switch Fabric 技术解析
服务器·c语言·嵌入式硬件·php·fabric