C 语言时间获取

第一方法:

#include <time.h>
 time_t time(time_t *tloc);
功能:计算从1970年1月1日0时0分0秒   到  此时此刻的秒数
参数:保存秒数的变量地址在这里插入代码片
返回值:成功:返回获取的秒数
	失败:-1

ctime()
#include<stdio.h>
char *ctime(const time_t *timep);
功能:将标准时间转换为字符串
参数:---以秒为单位的时间的指针
返回值:	成功:表示时间的字符串
	失败:NULL

例子

#include<stdio.h>
#include<time.h>
int main()
{
	
	struct tm *tp;
	
	time_t t,ret;
	
	ret = time(&t);
	
	tp = localtime(&t);
	
	printf("time(&t) = %ld\n",time(&t));
	
	printf("ret = %ld\n",ret);
	
	printf("ctime(&t) = %s\n",ctime(&t));
	
}

第二种方法:

#include <time.h>
struct tm localtime(const time_t timep);
功能:将标准时间转换为本地时间
参数:以秒为单位的时间指针
返回值: 成功:返回结构体指针
失败:NULL
这是结构的成员
struct tm {
int tm_sec; /
 Seconds (0-60) /
int tm_min; /
 Minutes (0-59) /
int tm_hour; /
 Hours (0-23) /
int tm_mday; /
 Day of the month (1-31) /
int tm_mon; /
 Month (0-11) /
int tm_year; /
 Year - 1900 /
int tm_wday; /
 Day of the week (0-6, Sunday = 0) /
int tm_yday; /
 Day in the year (0-365, 1 Jan = 0) /
int tm_isdst;/
 Daylight saving time
/
};
例子:

#include<stdio.h>
#include<time.h>
int main()
{
	struct tm *tp;
	time_t t,ret;
	
	time(&t);
	
	tp = localtime(&t);
	
	printf(" 秒 = %d ",tp->tm_sec);
	printf(" 分 = %d ",tp->tm_min);
	printf(" 时 = %d ",tp->tm_hour);
	
	printf(" 这个月第%d天 ",tp->tm_mday);
	printf(" %d月 ",tp->tm_mon+1);///为什么要加1,请看结构体
	printf(" %d年 ",tp->tm_year+1900);
	
	printf(" 星期%d ",tp->tm_wday);
	printf(" 这年第%d天 ",tp->tm_yday);
	printf(" %d\n",tp->tm_isdst);//不知道
}
posted @ 2022-05-07 14:45  孤走  阅读(78)  评论(0编辑  收藏  举报