# contains "stdio.h"
int main(void)
{
struct tm * ptr
time _ t lt
Character string */
Int tm _ min/* minutes-The interval between values is */
Int tm _ hour/* when-value interval is */
Int tm _ mday/* Date in a month-the range is, where 0 means Sunday, 1 means Monday, and so on */
Int tm _ yday/* Number of days per year starting from 65438+1 October 1–the value range is, where 0 means 65438+1 October1and1means 65438+/kloc-0.
Int tm _ isdst/* daylight saving time identifier. When daylight saving time is implemented, tm_isdst is positive. Without daylight saving time, tm_isdst is 0; When the situation is unknown, Tm_isdst () is negative. */
};
#define _TM_DEFINED
#endif
The ANSI C standard says that the time of using tm structure is expressed as breakdown time. Calendar time is represented by the data type of time_t, and the time represented by time_t is the number of seconds from a certain point in time (for example: 1970 65438+ 10 month 1: 00: 00). In time.h, we can also see that time_t is a long integer:
#ifndef _TIME_T_DEFINED
typedef long time _ t; /* Time value */
#define _TIME_T_DEFINED /* Avoid defining time_t */
#endif
You may wonder: Since time_t is actually a long integer, what should I do if the number of seconds from a certain point in time (generally 1970 65438+65438 10: 00: 00 on October) to that point in time (that is, calendar time) is beyond the range that a long integer can represent? For the value of time_t data type, the time it represents cannot be later than 65438+ 18, 19: 08, 2038+ 14: 07. In order to express a longer time, some compiler manufacturers have introduced 64-bit or even longer integers to save calendar time. For example, Microsoft uses __time64_t data type to save the calendar time in Visual C++, and obtains the calendar time through _time64 () function (instead of using 32-bit time () function), which can save 300 1 year 1 month 1 day at 0: 00: 00 (.
In the header file of time.h, we can also see some functions with time_t as parameter type or return value type:
double difftime(time _ t time 1,time _ t time 0);
time _ t mktime(struct TM * time ptr);
time _ t time(time _ t * timer);
char * ASC time(const struct TM * time ptr);
char * ctime(const time _ t * timer);
In addition, time.h also provides two different functions to convert the calendar time (an integer represented by time_t) into the time format tm that we usually see to display the year, month, day, minute and second respectively:
struct TM * GM time(const time _ t * timer);
struct TM * local time(const time _ t * timer);
By consulting MSDN, we can know that the value of time point in Microsoft C/C++ 7.0 (the value of time_t object) is the number of seconds from189965438+February 3 1 to this time point, while other versions of Microsoft C/C++ and all different versions of Visual C++ are calculated from 60.
4. Functions related to date and time and their applications
In this section, I will show you how to use the functions declared in time.h to manipulate time. These operations include obtaining the current time, calculating the time interval, displaying the time in different forms and so on.
4. 1 Get the calendar time
We can get the calendar Time through the time () function, and its prototype is: time _ t time (time _ t * timer);
If the parameter timer has been declared, you can return the current calendar time from the parameter timer, or you can return the current calendar time by returning the value, that is, the number of seconds from a certain time point (for example: 1970 1.00+0.00) to the current time. If this parameter is null, the function will return the current calendar time only by the return value, as shown in the following example:
# contains "time.h"
# contains "stdio.h"
int main(void)
{
struct tm * ptr
time _ t lt
Lt = time (nul);
Printf ("The current calendar time is %d\n", lt);
Returns 0;
}
The result of the operation is related to the time at that time. The result of my operation at that time was:
The current calendar time is1122707619.
Where 1 122707 19 is the calendar time when I run the program. That is, seconds from 1970 65438+ 10 month 1, 0: 00, 0: 00.
4.2 Purchase Date and Time
The date and time mentioned here are the information we usually say such as year, month, day, hour, minute and second. From section 2, we already know that all this information is saved in a structure called tm, so how to save a calendar time as an object with tm structure?
The functions that can be used are gmtime () and localtime (), and the prototypes of these two functions are:
struct TM * GM time(const time _ t * timer);
struct TM * local time(const time _ t * timer);
The gmtime () function converts the calendar time into universal standard time (GMT) and returns a tm structure to save the time, while the localtime () function converts the calendar time into local time. For example, the universal time obtained by using the gmtime () function is 7: 00 on July 30th, 2005, so the local time obtained by using the localtime () function in China will be 8 hours later than the universal time, that is, July 30th, 2005 is 65,438+08: 20. Here's an example:
# contains "time.h"
# contains "stdio.h"
int main(void)
{
struct tm * local
time _ t t
T = time (nul);
local=localtime。 t);
Printf ("local time is: %d\n", Local-& gt;; TM _ hour);
local=gmtime。 t);
Printf("UTC hour is: %d\n ",local-& gt;; TM _ hour);
Returns 0;
}
The running result is:
The local time is: 15
UTC time is: 7.
4.3 fixed time format
We can display the time in a fixed format through asctime () function and ctime () function, and the return values of both functions are char * strings. The returned time format is:
Day, month, day, hour: minute: second year \n\0
For example: wedjan 02 02: 03: 551980 \ n \ 0
Where \n is a line break and \0 is a null character, indicating the end of the string. The following are prototypes of two functions:
char * ASC time(const struct TM * time ptr);
char * ctime(const time _ t * timer);
Among them, asctime () function is to generate a fixed format string for saving time information through tm structure, while ctime () is to generate a time string through calendar time. In this case, the asctime () function only needs to fill the fields in the tm structure object in the corresponding position of the time string, while the ctime () function needs to refer to the local time setting, convert the calendar time into the local time, and then generate the formatted string. Next, if t is a non-empty time_t variable, then:
printf(ctime(& amp; t));
Equivalent to:
struct tm * ptr
ptr=localtime。 t);
printf(ASC time(ptr));
Then, the output results of the two printf statements in the following program are different (unless you set the local time zone as the time zone of universal standard time):
# contains "time.h"
# contains "stdio.h"
int main(void)
{
struct tm * ptr
time _ t lt
Lt = time (nul);
ptr = gmtime(& lt; );
printf(ASC time(ptr));
printf(ctime(& lt; ));
Returns 0;
}
Running results:
Saturday, 30 July 2005 08: 43: 03
Saturday, 30 July 2005 16:43:03
4.4 Custom Time Format
We can use the strftime () function to format the time we want. Its prototype is as follows:
size_t strftime(
char *strDest,
size_t maxsize,
Const char * format,
const struct tm *timeptr
);
We can put the time information saved in timeptr into the string pointed by strtest according to the format command pointing to the string, and the maximum number of maxsize characters is stored in strtest. This function returns the number of characters in the string pointed by strDest.
The operation of strftime () function is somewhat similar to sprintf (): it recognizes the format command set starting with percent sign (%) and puts the print format result in a string. The format command explains the exact representation of various date and time information in the string strDest. Other characters in the format string are put into the string as they are. The format commands are listed below. They are case-sensitive.
Abbreviation for day of the week%.
Full name of% day of the week.
Abbreviation for %b month minutes
Full name of %B month
Time series of %c standard dates
Last two digits of %C year
What day of the month does %d represent in decimal?
%D month/day/year
%e In the two-character field, what day of the month is expressed in decimal?
%F year-month-day
Last two digits of year %g, using week-based year.
%G years, using week-based years
Short month name of %h
%H 24-hour clock
%I 12 hours
What day of the year does %j represent in decimal?
%m decimal month
%M minutes in decimal time
%n new line character
%p equivalent display of local AM or PM.
%r 12 hours
%R displays hours and minutes: hh: mm
Fractional seconds of %S
%t horizontal tab
% t is displayed in minutes and seconds: hh:mm:ss.
%u What day is Monday, the first day (values range from 0 to 6, and Monday is 0)?
%U Sunday is the first day of the week of the year (value from 0 to 53)?
%V What week ordinal of a year, use a week-based year.
%w What day of the week is it (values range from 0 to 6, and Sunday is 0)
%W What week ordinal of a year is Monday the first day (value between 0 and 53)?
%x standard date string
Time series of %X standard
%y Decimal year without century (value from 0 to 99)
Decimal year of %Y with century part
%z, %Z Time zone name, or empty character if time zone name cannot be obtained.
%% percent symbol
If you want to display what time it is, and display 12 hour, just like the following program:
# contains "time.h"
# contains "stdio.h"
int main(void)
{
struct tm * ptr
time _ t lt
String [80];
Lt = time (nul);
ptr = local time(& lt; );
Strftime(str, 100, "Now it's %I %p", ptr);
printf(str);
Returns 0;
}
The running results are as follows:
It's 4 p.m.
The following program displays the current completion date:
# include & ltstdio.h & gt
# include & lttime.h & gt
Invalid master (invalid)
{
struct tm * newtime
char tmpbuf[ 128];
time _ t lt 1;
Time (< 1);
new time = local time(& lt; 1);
Strftime( tmpbuf, 128, "Today is the %d day %A of year %Y, \n", newtime);
printf(tmpbuf);
}
Running results:
Today is Saturday, July 30th, 2005.
4.5 Calculate the length of the duration
In practical applications, it is sometimes necessary to calculate the duration of an event, such as calculating the typing speed. In the timing part of 1, I have given an example with the clock function. The Clock () function can be accurate to the millisecond level. At the same time, we can also use the difftime () function, but it can only be accurate to seconds. This function is defined as follows:
double difftime(time _ t time 1,time _ t time 0);
Although the time interval in seconds returned by this function is of type double, it does not mean that time has the same precision as double, which is felt by its parameters (time_t is calculated in seconds). For example, the following program:
# contains "time.h"
# contains "stdio.h"
# contains "stdlib.h"
int main(void)
{
Time_t starts and ends;
Start = time (nul);
System ("suspended");
End = time (nul);
Printf ("Paused for %f seconds. \n ",difftime(end,start)); //& lt; -
System ("suspended");
Returns 0;
}
The running results are as follows:
Please press any key to continue ...
The pause took 2.0000000 seconds.
Please press any key to continue ...
As you can imagine, the pause time is not so coincidental as 2 seconds. In fact, you use the above program as "//
Printf ("Paused for %f seconds. \n ",end-start);
The running result is the same.
4.6 Turn time warp into calendar time.
The decomposition time mentioned here is the time structure saved in units of year, month, day, hour, minute and second, which is the tm structure in C/C++. We can use mktime () function to convert the time represented by tm structure into calendar time. Its functional prototype is as follows:
time _ t mktime(struct TM * time ptr);
The return value is the converted calendar time. In this way, we can do a decomposition time first, and then operate on this time. The following example can calculate the date of the week of July 1997 1:
# contains "time.h"
# contains "stdio.h"
# contains "stdlib.h"
int main(void)
{
struct TM t;
Time of day;
t . TM _ year = 1997- 1900;
t . TM _ mon = 6;
t . TM _ mday = 1;
t . TM _ hour = 0;
t . TM _ min = 0;
t . TM _ sec = 1;
t . TM _ isdst = 0;
t _ of _ day = mktime(& amp; t);
printf(ctime(& amp; t _ of _ day);
Returns 0;
}
Running results:
Tuesday 06 5438+0 00: 00: 06 5438+01997
Now notice that with the mktime () function, can we operate at any time before now? Can you work out the day of August 1945 by this method? The answer is no, because this time is before 1970 65438+ 10/month, so in most compilers, although such a program can be compiled, its runtime will terminate abnormally.
summary
This paper introduces the concepts of date and time in standard C/C++, and tells the usage of these functions and data structures through various examples. The author thinks that some concepts related to time are very important. Understanding these concepts is the basis of understanding various time format transformations and applying these functions and data structures.