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;
}

运行结果:

相关推荐
java 乐山20 分钟前
c 写一个文本浏览器(1)
c语言·开发语言
windows_634 分钟前
MISRA C:2025 规则逐条分析
c语言·开发语言
郝学胜-神的一滴2 小时前
深入解析C/S架构与B/S架构:技术选型与应用实践
c语言·开发语言·前端·javascript·程序人生·架构
yuyousheng3 小时前
CentOS7更换为阿里源
linux·c语言
进击的小头3 小时前
结构型模式:适配器模式(C语言实现与底层实战)
c语言·适配器模式
EmbedLinX4 小时前
一文理解后端核心概念:同步/异步、阻塞/非阻塞、进程/线程/协程
linux·服务器·c语言·网络
人间不清醒ab5 小时前
FREERTOS检测任务栈内存情况
c语言·单片机
Amber7626 小时前
嵌入式C函数参数设计深度解析:指针与值传递的实战艺术
c语言·开发语言
散峰而望7 小时前
【数据结构】假如数据排排坐:顺序表的秩序世界
java·c语言·开发语言·数据结构·c++·算法·github
爱编码的小八嘎7 小时前
c语言对话-2.空引用
c语言