A function of time, making you a strong man in control of time

I was probably tired and couldn't be happy either sideways or vertically. I stood up and frowned. There was no reason for this sadness. As a junior programmer who has been unable to control the system time for a long time, after a few days of exploration, I summarized it on a whim and shared it with my friends. Friends may be looking forward to it, how does a blog make itself a powerhouse in controlling time ? It's useless to say more, start the text!

content

What's the date today?

time_t type: calendar time

time function: Get the current time in the form of calendar time

tm structure: disintegration time (tear time)

localtime function: converts calendar time to decomposed time representing local time

gmtime function: convert calendar time to UTC decomposition time

asctime function: convert the decomposed time to a string

ctime function: convert calendar time to string

difftime function: find time difference

ask for the week

mktime function: pole reversal

end


What's the date today?

Let's start with the first code of this blog, and let's learn how to get the current date and time:

//time01

#include <stdio.h>
#include <time.h>

void put_date(const struct tm* timer)
{
	char* wday_name[] = { "日","一","二","三","四","五","六" };

	printf("%4d年%02d月%02d日(%s)%02d时%02d分%02d秒", timer->tm_year + 1900,      //年
		timer->tm_mon + 1,                  //月
		timer->tm_mday,                     //日
		wday_name[timer->tm_wday],          //星期
		timer->tm_hour,                     //时
		timer->tm_min,                      //分
		timer->tm_sec);                     //秒
}

int main()
{
	time_t current;                     //日历时间
	struct tm* timer;                   //分解时间(结构体)

	time(&current);                     //获取当前时间
	timer = localtime(&current);        //转换成分解时间(本地时间)

	printf("当前日期和时间是");
	put_date(timer);
	printf("。\n");

	return 0;
}

time_t type: calendar time

The time_t type, also known as the calendar time , is actually an arithmetic type that can perform addition, subtraction, multiplication and division operations just like the int and double types. Which type is equivalent to depends on the programming environment (not only the type of calendar time, but also its specific value). Using it requires adding the <time.h> header file definition. In most compilation environments, the time_t type is equivalent to the int type or the long type, and the Greenwich Mean Time, that is, the number of seconds elapsed after January 1, 1970 0:0:0:0, is used as the specific value of the calendar time.

time function: Get the current time in the form of calendar time

And look at the table below:

time
head File #include <time.h>
Format time_t time(time_t *timer);
Features Determines the current calendar time. The representation of this value is not defined
return value Returns the calculated calendar time with the best approximation in the environment in which it is compiled. If the calendar time is invalid, the return value (time_t) is 1. When the timer is not a null pointer, the return value is assigned to the object pointed to by the timer.

On the basis of finding the calendar time, this function stores the calendar time in the object pointed to by the parameter timer, and returns the calendar time at the same time. Therefore, we can choose various calling methods according to different uses and personal preferences.

We pass a pointer to the variable current as an argument to the time function by using time(¤t);.

tm structure: disintegration time (tear time)

Try to use the time_t type to represent time. We know that it represents something that is extremely difficult for us to understand:

Therefore, we can use another representation method, which is called the tm structure type of tearing time .

Let's take a look at the tm structure :

struct tm{
    int tm_sec;            //秒(0-61)
    int tm_min;            //分(0-59)
    int tm_hour;           //时(0-23)
    int tm_mday;           //日(0-31)
    int tm_mon;            //从一月开始的月份(0-11)
    int tm_year;           //从1900开始的年份
    int tm_wday;           //星期:星期日-星期六(0-6)
    int tm_yday;           //从1月1日开始的天数(0-365)
};

Friends can understand the value represented by each member through the comments in the code. And when we browse to the second member tm_min value is set to 0-61 , because the "leap second" is taken into account .

localtime function: converts calendar time to decomposed time representing local time

The localtime function (via the tm structure) is used to convert a calendar time value to a decomposed time.

localtime
head File #include <time.h>
Format struct tm*localtime(const time_t *timer);
Features Converts the calendar time pointed to by timer to the decomposed time expressed in local time
return value Returns a pointer to the converted object

As the literal of locattime is indicated by four, what you get after conversion is the local time. Let's take a look at its representation:

 Finally, let's analyze the time01 program.

(1) In the main function, we use the time function to obtain the current time in the form of a time_t calendar time, and convert it into a decomposed time, that is, a tm structure.

(2) How to use put_date to accept the converted structure and display the decomposition time in the Gregorian era;

(3) Finally, add 1900 to tm_year, and add 1 to tm_mon. Since the tm_wday representing the week corresponds to 0 to 6 from Sunday to Saturday, the array wday_name can be used to convert it to the Chinese string "日", "One",..."Six" and displayed.

gmtime function: convert calendar time to UTC decomposition time

It is too stingy to only talk about local time. Next, I will bring the coordinated time (ie UTC) to my friends.

The gmtime function is the function used to execute UTC, see the table below;

gmtime
head File #include <time.h>
Format struct tm *gmtime(const time_t *timer);
Features Converts the calendar time pointed to by timer to the decomposed time expressed in coordinated time
return value Returns a pointer to the converted object

Let's take a look at how to use the gmtime function, the code is actually the same as time01:

//time02

#include <stdio.h>
#include <time.h>

void put_date(const struct tm* timer)
{
	char* wday_name[] = { "日","一","二","三","四","五","六" };

	printf("%4d年%02d月%02d日(%s)%02d时%02d分%02d秒", timer->tm_year + 1900,
		timer->tm_mon + 1,
		timer->tm_mday,
		wday_name[timer->tm_wday],
		timer->tm_hour,
		timer->tm_min,
		timer->tm_sec);
}

int main()
{
	time_t current;
	struct tm* timer;

	time(&current);
	timer = gmtime(&current);

	printf("当前日期和时间用UTC表示是");
	put_date(timer);
	printf("。\n");

	return 0;
}

In fact, it is to change timer = localtime(¤t); to timer = gmtime(¤t); .

asctime function: convert the decomposed time to a string

Let me share a function with my friends, it can convert the decomposition time into a string, and can simply represent the current date and time, why not do it? And look at the following code:

//time03

#include <stdio.h>
#include <time.h>

int main()
{
	time_t current = time(NULL);

	printf("当前日期和时间:%s", asctime(localtime(&current)));

	return 0;
}

The asctime function is a function that converts the decomposed time into string form. The strings it generates and returns are in the order of week/month/day/hour/minute/second/year from left to right, separated by whitespace characters and colons ":" .

 We can see that there are 3 letters at the beginning of their English words in the week and month respectively (the first letter is an uppercase letter, and the second and third are lowercase letters). Let's take a look at its table again:

asctime
head File #include <time.h>
Format char *asctime(const struct tm *timeptr);
Features

Convert the decomposition time of the structure pointed to by timeptr into a string of the following form

Sun Apr 10 13:13:09:00 2022

return value Returns a pointer to the converted object

ctime function: convert calendar time to string

When using the asctime function, in order to convert the calendar time of the time_t type into the decomposition time of the tm structure, we need to call the localtime function. In this way, it takes two steps to convert the calendar time to a string, which is too cumbersome. The ctime function is different, it only takes one step!

//time04

#include <stdio.h>
#include <time.h>

int main()
{
	time_t current = time(NULL);

	printf("当前日期和时间:%s", ctime(&current));

	return 0;
}

The ctime table is as follows:

ctime
head File #include <time.h>
Format char *ctime(const time_t *timer);
Features Convert the calendar time pointed to by timer to the local time in the same string form as the asctime function, equivalent to asctime(localtime(timer))
return value Returns the pointer returned by the asctime function with the decomposition time as the actual parameter

difftime function: find time difference

Next, I will show you how to use the calendar time obtained by the time function to calculate the processing time. Code first:

//time05

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int a, b, c, d;
	int x;
	time_t start, end;

	srand(time(NULL));

	a = rand() % 100;
	b = rand() % 100;
	c = rand() % 100;
	d = rand() % 100;

	printf("%d+%d+%d+%d等于多少:", a, b, c, d);

	start = time(NULL);

	while (1)
	{
		scanf("%d", &x);
		if (x == a + b + c + d)
			break;
		printf("回答错误!!\n请重新输入:");
	}

	end = time(NULL);

	printf("用时%.0f秒。\n", difftime(end, start));

	return 0;
}

p rintf("Time %.0f seconds.\n", difftime(end, start)); Used to find the difference between two calendar times by calling the difftime function. Its usage is extremely simple, just give two values ​​of type time_t as parameters (end-start), and return the time difference in the form of a double type value in seconds.

Let's take a look at the difftime table again:

difftime
head File #include <time.h>
Format double difftime(time_t time1,time_t time0);
Features Calculate the difference between two calendar times time1 - time0
return value Represents the obtained time difference in seconds, returned as a double

ask for the week

mktime function: pole reversal

I have described how to convert calendar time into decomposed time. Now I will talk about how to convert the decomposed time of local time into calendar time. That is to use the mktime function, which is the opposite of the conversion performed by the localtime function.

而且,这函数还带来了意外之喜它可以计算并设定结构体的星期和一年中经过的天数的值。利用该功能的话,咱只需设定分解时间的年/月/日并调用mktime 函数,就能求出对应的星期。

我们来看看它的流程图:

这可真是两极反转啊!

最后,用一段华丽的代码了却此博客:

//time06

#include <time.h>
#include <stdio.h>

int dayofweek(int year, int month, int day)
{
	struct tm t;
	t.tm_year = year - 1900;
	t.tm_mon = month - 1;
	t.tm_mday = day;
	t.tm_hour = 0;
	t.tm_min = 0;
	t.tm_sec = 0;
	t.tm_isdst = -1;

	if (mktime(&t) == (time_t)-1)
		return -1;
	return t.tm_wday;
}

int main()
{
	int y, m, d, w;
	char* ws[] = { "日","一","二","三","四","五","六" };

	printf("求星期。\n");
	printf("年:");		scanf("%d", &y);
	printf("月:");		scanf("%d", &m);
	printf("日:");		scanf("%d", &d);

	w = dayofweek(y, m, d);

	if (w != -1)
		printf("这一天是星期%s。\n", ws[w]);
	else
		printf("无法求出星期。\n");

	return 0;
}

time06 中定义的dayofweek 函数会根据接受的年/月/日这3个值来生成分解时间,然后再调用mktime 函数,之后函数会通过”附赠“的功能直接返回成员函数tm_wday 中设定的值,值为0是星期日……

此外,mktime函数返回错误时,说明程序有可能求出了错误的星期数值,因此函数dayofweek 会返回 -1

完结

感激阅读到这里的你,相信阅读完的你已经成为了掌控时间的强者了吧!精彩并不止于这些,学有余力的小伙伴可以看看下面这些博客,都是有着极多的技巧与干货❤!

C语言小游戏(一)----猜数游戏_施律.的博客-CSDN博客_c语言猜数游戏次数限制

《斗破CPP》 第壹章 ---- 初窥CPP_施律.的博客-CSDN博客

《斗破CPP》 第贰章(上) ---- 初识分支句_施律.的博客-CSDN博客

如果觉得本篇博客对正在学习编程的你有帮助的话,请给施律.多一点的支持与关注!未来的一段时间里施律.将和小伙伴们一起在编程的道路是越来越远,希望下次的我能为大家奉上更好的博客内容,也希望下次的博客有你

Guess you like

Origin blog.csdn.net/qq_64263760/article/details/124075069