基础时间函数总结(c语言)

头文件:<time.h>

time_t:数据类型   用来得到当前系统日历时间

            使用方式:time_t 变量名=time(NULL);//得到当前时间

localtime 函数:用来将系统时间存放在结构体 struct tm 中,其返回值是struct tm*类型

struct tm :系统已经定义好的结构体,用来打印当前时间,年月之类的

                struct tm 是结构体类型,不可以写成struct am,struct bm之类的哟!

                 注意:在定义struct tm 的结构体名时若是使用localtime必须是struct tm *

                 strcut tm 结构体内部已经定义好了元素,在使用时可以直接调用。

struct tm的内部元素如下:

strcut tm

{

         数据类型         内容          取值范围

        int tm_sec:      秒                0~59

        int tm_min:      分                0~59

        int tm_hour:       时                0~23

        int tm_mday:      日                1~31

        int tm_mon:        月                0~11     使用时记得+1

        int tm_year:        年               +1900   

                                  例:表示今年 : 结构体名->tm_year + 1900

        int tm_wday:      星期几           0~6      可自定义函数表示对应星期几

        int tm_yday:     今年第几天     0~365   使用时记得+1

}

asctime函数:打印出当前年月日等信息(字符串的形式)

                       形式: printf("%s",asctime(struct tm *b));

不多bb直接上代码:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
char* wday(int a);//定义一个函数,使tm_wday中的数字对应成星期几的汉字,返回指针
int main()
{
	time_t a = time(NULL);
    struct tm *b = localtime(&a);//注意b的类型是指针呦
	printf("总体时间为:n");
	printf("%s", asctime(b));//注意是字符串的形式,用%s
	printf("今天是%d年%d月%d日", b->tm_year + 1900,b->tm_mon +1,b->tm_mday );
	printf("%s", wday(b->tm_wday));
	printf("n当前时间:%d:%d:%d", b->tm_hour, b->tm_min, b->tm_sec);
	printf("n今天是今年的第%d天", b->tm_yday + 1);

	return 0;
}
char* wday(int a)
{
	char* p=(char *)malloc(4*sizeof(char));//动态开辟内存空间存放字符串
	switch (a)
	{
	case 0: strcpy(p, "星期日"); return p;
	case 1: strcpy(p,"星期一"); return p;
	case 2: strcpy(p,"星期二"); return p;
	case 3: strcpy(p,"星期三"); return p;
	case 4: strcpy(p,"星期四"); return p;
	case 5: strcpy(p,"星期五"); return p;
	case 6: strcpy(p,"星期六"); return p;
	}
}

运行结果:

总体时间为:
Tue Dec 14 09:52:57 2021
今天是2021年12月14日星期二
当前时间:9:52:57
今天是今年的第348天
--------------------------------
Process exited after 0.08462 seconds with return value 0
请按任意键继续. . .

            博主不要脸的想求个三连支持?~

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>