//
# contains "stdafx.h"
# include & ltiostream & gt
Use namespace std
# include & ltctime & gt
int main(int argc,char* argv[])
{
Time_t now_time= time (empty); ;
char tmp[64];
Strftime (tmp, sizeof (tmp), "%y/%m/%d% x% a %j day% z" local time this year (&; now _ time));
cout & lt& lttmp & lt& ltendl
Returns 0;
}
1. Concept In C/C++, there are many noticeable problems in string manipulation. Similarly, the operation of time in C/C++ also has many noteworthy places. Recently, many netizens in the technical group have asked many questions about the operation, acquisition and display of time in C++ language.
Clock ticking: Clock ticking unit (not called clock ticking). The time of the clock ticking unit is controlled by the central processor.
Clock beat is not a clock cycle of CPU, but a basic time unit of C/C++. We can use ANSI standard library
Time.h header file. The method used to define time and date in this header file, whether it is structural definition or naming, is very clear.
Obvious c language style. Next, I will explain how to use the time function of date in C/C++.
2. The timing function in timing C/C++ is clock (), and its related data type is clock _ t. In MSDN, the clock function is checked correctly.
The definition is as follows: clock _ tclock (void); This function returns from "Start this program process" to "Call the clock () function in the program"
The number of ticks between CPU clocks is called wall clock in MSDN. Where clock_t is used for
The data type of the save time can be defined in the time.h file:
# ifndef _ CLOCK _ T _ DEFINED typedef long CLOCK _ T;
# Definition _ Clock _ Time _ Definition
#endif
Obviously, clock_t is a long integer.
In the time.h file, a constant CLOCKS_PER_SEC is also defined to indicate how many clock units there will be in one second.
It is defined as follows:
# Define the number of clocks per second ((clock_t) 1000)
You can see that every thousandth of a second (1 millisecond),
The value returned by calling the clock () function plus 1.
For example, you can use the formula clock()/CLOCKS_PER_SEC to calculate the running time of the process itself:
void elapsed_time()
{
Printf ("Running time: %u seconds. /n ",clock()/CLOCKS _ PER _ SEC);
}
Of course, you can also use the clock function to calculate how long it takes for your machine to run a cycle or handle other events:
# including "stdio.h"
# including "stdlib.h"
#i includes "time.h"
int main( void ) {
Dragon I =1000000l;
Clock_t starts and ends;
Double duration;
Printf ("The time to do %ld empty loops is", i);
Start = clock (); while(I-);
finish = clock();
duration =(double)(finish-start)/CLOCKS _ PER _ SEC;
Printf( "%f seconds /n ",duration);
System ("suspended");
}
On the author's machine, the running results are as follows:
The time to do 1000000 empty cycles is 0.03000 seconds.
Above we see that the length of the clock timing unit is 1ms, so the timing accuracy is also1ms.
So can we change the definition of CLOCKS_PER_SEC and make it bigger?
So the timing accuracy is higher?
By trying, you will find it impossible.
In the standard C/C++, the minimum time unit is 1 millisecond.
3. Data structure related to date and time in standard C/C++, we can get the date and time through tm structure.
The definition of tm structure in time.h is as follows:
#ifndef _TM_DEFINED struct tm
{ int tm _ sec
int tm _ min
int tm _ hour
int tm _ mday
int tm _ mon
int tm _ year
int tm _ wday
int tm _ yday
int tm _ isdst
};
#define _TM_DEFINED
#endif
The ANSI C standard says that the time of using tm structure is expressed as breakdown time.
And the calendar time is represented by data type time_t, and the time is represented by time_t (calendar time).
Is the number of seconds from a time point (for example: 1970 65438+ 10 month 1: 00: 00) to this time point.
In time.h, we can also see that time_t is a long integer:
# ifndef _ TIME _ T _ DEFINED typedef long TIME _ T;
# Define Time Time Definition
#endif You may have questions: Since time_t is actually a long integer, one day in the future,
The number of seconds from a time point (generally 1970 1: 00, 10/0: 00) to that time point (that is, the calendar time) cannot be expressed by long shaping.
What about the range of numbers?
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 the __time64_t data type in Visual C++ to save calendar time.
And get the calendar time through the _time64 () function (instead of using the time () function of 32-bit words),
In this way, the time before 300 1 year 1 month 1 day (excluding this time point) can be saved with this data type.
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 what we usually see.
Time format tm showing year, month, day, hour and minute respectively:
struct TM * GM time(const time _ t * timer);
struct TM * local time(const time _ t * timer);
By consulting MSDN, we can know the value of time point (the value of time_t object) in Microsoft C/C++ 7.0.
Is the number of seconds that passed from 1899, 12, 3 1 this day to that time point, while other versions of Microsoft C/C++ and all.
Different versions of Visual C++ are counted from 0: 00: 00 and 0: 00 on 197065438+ 10/day.
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 you have declared the parameter timer, you can return the current calendar time from the parameter timer.
At the same time, you can also return the current calendar time by returning the value, that is, starting from a certain time point (for example: 1970 65438+ 10: 00/0: 00 on October).
The number of seconds so far. If the parameter is NULL, the function will return the current calendar time only by returning the value.
For example, the following example is used to display the current calendar time:
# including "time.h" #
Including "stdio.h"
int main(void) {
struct tm * ptr
time _ t lt
Lt = time (empty);
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 Obtaining Date and Time The date and time mentioned here is what we usually call information such as year, month, day, hour, minute and second.
From section 2, we already know that all this information is stored in a structure called tm.
So how do you save a calendar time as an object with tm structure?
The functions that can be used are gmtime () and localtime ().
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 (Greenwich Mean Time),
And return a tm structure to save this time, and the localtime () function is to convert the calendar time into local time.
For example, the universal standard time obtained by using the gmtime () function is 7: 00 on July 30th, 2005, 18 minutes and 20 seconds.
Then the localtime I got with the local time () function in China will be 8 hours later than the standard time.
That is, July 30th, 2005 15: 08, 18: 20. Here's an example:
#i includes "time.h"
# including "stdio.h"
int main(void) {
struct tm * local
time _ t t
T = time (empty);
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: local time is: 15 UTC time is: 7.
4.3 Fixed time format We can display the time in a fixed format through the asctime () function and the ctime () function.
The return values of both are char * strings.
The returned time format is: day of the week, date, hour, minute, second year /n/0.
For example: wedjan 02 02: 03: 551980 /n /0 where/n is a line break and/0 is an empty 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);
The asctime () function is a fixed format string generated by tm structure.
Ctime () is a time string generated by calendar time.
In this case, the asctime () function only fills the fields in the tm structure object at the corresponding position of the time string.
The ctime () function needs to refer to the local time setting to convert the calendar time into local time.
And then generate a formatted string. Next, if lt is a non-empty time_t variable,
Then: printf (ctime (
Then, the output results of the two printf statements in the following program are different (unless you set the local time zone to universal standard time).
Time zone):
#i includes "time.h"
# including "stdio.h"
int main(void)
{ struct tm * ptr
time _ t lt
Lt = time (empty);
ptr = gmtime(& lt; );
printf(ASC time(ptr));
printf(ctime(& lt; ));
Returns 0;
}
Operation result: July 30, 2005, 08: 43: 03.
4.4 Customize the time format We can use strftime () function to format the time into the format we want.
Its prototype is as follows:
size_t strftime( char *strDest,size_t maxsize,const char *format,const struct TM * time ptr);
We can put the time information saved in timeptr into the string pointed by strDest according to the format command pointing to the string.
Store maxsize characters in strDest at most. This function returns the number of characters in the string pointed by strDest.
The strftime () function operates somewhat like sprintf (): it identifies a set of format commands that start with a percent sign (%).
Print format results are placed 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 of day of week %a Full name of day of week %b Abbreviation of month %B Full name of month %c Standard date time series %C Year
The last two digits %d represent the day of the month in decimal %D month/day/year %e in the two-character field, the day of the month in decimal.
Last two digits of Day %F Year-Month-Day %g year, using week-based year %g year minutes and week-based year %h to abbreviate months.
Name% h hour in 24-hour system% I 12 hour system %j decimal date %m decimal month in a year.
Minutes in decimal time of %M% nNew line% pEquivalent display of local AM or PM% r 12 hours% rDisplay hours
And minutes: hh:mm %S decimal seconds% t Minutes displayed on the horizontal tab% t: hh:mm:ss %u Day of the week, day of the week?
One is the first day (value from 0 to 6, Monday is 0) %U Which week of the first year, and Sunday is the first day (value from 0 to 53) %V every
The week ordinal of a year, the day ordinal of a year (values range from 0 to 6, and Sunday is 0) %w is expressed in decimal according to the week.
Take Monday as the first day (value from 0 to 53) %x standard date string %x standard time string %y decimal year without century.
(Values range from 0 to 99) %Y Decimal year %z with century part, %Z time zone name, or empty character if time zone name cannot be obtained.
%% percent sign If you want to display what time it is, use 12 hour to display it, just like the following program:
#i includes "time.h"
# including "stdio.h"
int main(void)
{
struct tm * ptr
time _ t lt
String [80];
Lt = time (empty);
ptr = local time(& lt; );
Strftime(str, 100, "Now it's %I %p", ptr);
printf(str);
Returns 0;
}
The running result is: it's 4 pm now, and the following program shows the current completion date:
#i includes
#i includes
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 in %B in% y/n year", new time);
printf(tmpbuf);
}
Operation result: Today is Saturday, July 30th, 2005.
4.5 Calculating Duration Sometimes in practical applications, it is 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 only to the second. This function is defined as follows:
double difftime(time _ t time 1,time _ t time 0);
Although the interval in seconds returned by this function is of type double,
But this does not mean that time has the same accuracy as double, which is felt by its parameters (time_t is calculated in seconds).
. For example, the following program:
#i includes "time.h"
# including "stdio.h"
# including "stdlib.h"
int main(void) {
Time_t starts and ends;
Start = time (empty);
System ("suspended");
End = time (empty);
Printf ("Paused for %f seconds. /n”,difftime(end,start));
//& lt; -System ("suspended");
Returns 0;
}
The running result is: Please press any key to continue ... It took 2.0000000 seconds to pause. Please press any key to continue ... as you can imagine.
The pause time is exactly 2 seconds, which is not so coincidental. In fact, you use the above program as "//
In: printf ("Paused for% f seconds. /n”,end-start); The running result is the same.
4.6 Decomposition time is converted into calendar time. The decomposition time mentioned here is the time structure saved in components such as year, month, day, hour, minute and second.
In C/C++, it is tm structure. 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 calculate a decomposition time first, and then operate this time.
The following example can calculate the day of July 1997:
#i includes "time.h"
# including "stdio.h"
# including "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 result: tuejule 0100: 0011997 Now, with the mktime () function, can we operate now?
Have you ever had it before? Can you work out the day of August 1945 by this method? The answer is no. Because this time
10 before 0970+65438+ 1, so in most compilers, although this kind of program can be compiled, its runtime will terminate abnormally.
5. This paper introduces the concepts of date and time in standard C/C++, and describes these functions and data structures through various examples.
How to use it. The author thinks that some concepts related to time are quite important, and understanding these concepts means understanding the transformation of various time formats.
Foundation is the basis for applying these functions and data structures.