How to get a summary of dates and times in C + +:
Starting with the introduction of the basic concept, this paper discusses the data structure and function used in the C + + time operation, and expounds the timing, time acquisition, time calculation and display format. This article also shows you the detailed use of various functions and data structures declared in the Time.h header file through a number of examples.
Keyword: UTC (World Standard Time), Calendar time (Calendar hour), epoch (point in time), clock tick (chronograph unit)
1. Concept
There are a number of noteworthy issues with the operation of a string in C + +, as well as a lot of attention to the operation of time in C + +. Recently, many netizens in the technology group have also asked the question of the operation, acquisition and display of time in the C + + language. Below, in this article, I will mainly introduce the use of time and date in C + +.
You can have a lot of operations and time-of-use methods by learning a lot of the C + + libraries. But before you do, you need to know some of the concepts of "time" and "date", mainly the following:
Coordinated Universal time (UTC): Coordinated worlds, also known as World standard Times, is known as Greenwich Mean Time (Greenwich Mean time,gmt). For example, the time difference between the Chinese mainland and UTC is +8, which is utc+8. The United States is UTC-5.
Calendar time: The time that is represented by the "number of seconds elapsed from a standard point in time". This standard point of time for different compilers will vary, but for a compilation system, this standard point of time is constant, the compilation system time corresponding to the calendar time is measured by the standard time point, so you can say that the calendar time is "relative time", but no matter what time zone you are in, At the same time, the calendar time is the same for the same standard point.
Epoch: Point in time. The point-in-time is an integer in standard C + +, which is represented by the time of the moment and the number of seconds (that is, the calendar time) of the standard time point.
Clock tick: The clocking unit (rather than the number of ticks), the length of time a clock unit is controlled by the CPU. A clock tick is not a cycle of the CPU, but rather a basic unit of time in C + +.
We can use the Time.h header file in the ANSI standard library. The method used to define the time and date in this header file, both in terms of structure definition and naming, has a pronounced C-language style. Below, I'll show you how to use the time function of the date in C + +.
2. Timing
The timing function in C/s + + is clock (), and the data type associated with it is clock_t. In MSDN, the check for the clock function is defined as follows:
clock_t clock (void);
This function returns the number of CPU clock ticks (clock ticks) from "Open this program process" to "call clock () function in program", called Wall Clock Time (Wal-clock) in MSDN. Where clock_t is the data type used to hold the time, in the Time.h file, we can find the definition of it:
#ifndef _clock_t_defined
typedef long CLOCK_T;
#define _clock_t_defined
#endif
It is clear that clock_t is a long shaping number. In the Time.h file, you also define a constant clocks_per_sec, which is used to indicate how many clock units are in a second, defined as follows:
#define CLOCKS_PER_SEC ((clock_t) 1000)
You can see that every 1 per thousand seconds (1 milliseconds), the value returned by the call to the clock () function increases by 1. As an example, you can use the formula clock ()/clocks_per_sec to calculate the run time of a process itself:
void Elapsed_time ()
{
printf ("Elapsed time:%u secs.
", 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 loop or handle other events:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "stdio.h"
#include "Stdlib.h"
#include "time.h"
int main (void)
{
Long i = 10000000L;
clock_t start, finish;
Double duration;
/* Measure the duration of an event */
printf ("Time to does%ld empty loops is", i);
start = Clock ();
while (i--);
finish = Clock ();
Duration = (double) (finish-start)/clocks_per_sec;
printf ("%f seconds
", duration);
System ("pause");
}
On the author's machine, the results of the operation are as follows:
Time to does 10000000 empty loops is 0.03000 seconds
We can see that the clock timing unit is 1 milliseconds in length, and the accuracy of the timing is 1 milliseconds, so could we change the definition of the clocks_per_sec by making it larger, so that the timing is more accurate? By trying, you will find that this is not possible. In standard C/s + +, the smallest unit of timing is one millisecond.
3. Date and time-related data structures
in standard C + +, we can obtain the date and time by the TM structure, which is defined in Time.h as follows:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#ifndef _tm_defined
struct TM {
int tm_sec; /* seconds? The value interval is [0,59] */
int tm_min; /* min-value interval is [0,59] */
int tm_hour; /* When-the value interval is [0,23] */
int tm_mday; /* Date in one months-the value interval is [1,31] */
int Tm_mon; /* Month (starting from January, 0 for January)-the value range is [0,11] */
int tm_year; /* Year with a value equal to the actual year minus 1900 */
int tm_wday; /* Week? The value interval is [0,6], where 0 represents Sunday, 1 for Monday, and so on */
int tm_yday; /* Number of days starting from January 1 each year? The value interval is [0,365], where 0 represents January 1, 1 represents January 2, and so on.
int tm_isdst; /* Daylight Saving time identifier, the TM_ISDST is positive when daylight savings is applied. Without daylight saving time, TM_ISDST is 0 and TM_ISDST () is negative when the situation is not known. */
};
#define _tm_defined
#endif
The ANSI C standard says this time using the TM structure is expressed as the decomposition time (broken-down times).
The calendar time is represented by the time_t data type, and the time represented by time_t (calendar time) is the number of seconds from a point in time (for example: January 1, 1970 0:0 0 seconds) to this time. In Time.h, we can also see that time_t is a long integer number:
#ifndef _time_t_defined
typedef long time_t; /* Time value */
#define _TIME_T_DEFINED/* Avoid repeating definitions time_t */
#endif
One might wonder: since time_t is actually a long integer, what about the number of seconds (that is, calendar time) that is beyond the range that a long shape can represent in the future, from one point in time (typically January 1, 1970 0:0 0 seconds) to that time? For a value of the time_t data type, the time it represents cannot be later than January 18, 2038 19:14 07 seconds. To be able to represent a longer period of time, some compiler vendors introduced 64-bit or even longer shaping numbers to hold the calendar time. For example, Microsoft uses the __time64_t data type in Visual C + + to save the calendar time and to get the calendar time through the _time64 () function (rather than by using the 32-bit word () function). This allows you to save the time before January 1, 3001 0:0 0 seconds (excluding that point in time).
In the time.h header file, we can also see some functions, all of which are functions with time_t as parameter types or return value types:
Double Difftime (time_t time1, time_t TIME0);
time_t mktime (struct TM * timeptr);
time_t Time (time_t * timer);
char * asctime (const struct TM * timeptr);
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) to the time format TM that we normally see when the date and time are displayed separately:
struct TM * gmtime (const time_t *timer);
struct TM * localtime (const time_t * timer);
By looking at MSDN, we know that the value of the point-in-time (the value of the Time_t object) in Microsoft C + + + 7.0 is the number of seconds from December 31, 1899 0:0 0 seconds to that point in time, while other versions of Microsoft C + + And all of the different versions of Visual C + + are calculated as the number of seconds that elapsed from January 1, 1970 0:0 to 0 seconds to that point in time.
4. Functions and applications related to date and time
In this section, I'll show you how to use the functions declared in time.h to manipulate time. These actions include taking the current time, calculating the time interval, displaying the time in different forms, and so on.
4.1 Get Calendar Time
We can use the time () function to get the calendar times, which are prototyped as:
time_t Time (time_t * timer);
If you have declared the parameter timer, you can return the current calendar time from the parameter timer, and return the current calendar time by returning the value, that is, from a point in time (for example: January 1, 1970 0:0 0 seconds) to now the number of seconds. If the argument is empty (NUL), the function will return the current calendar time only by the return value, such as the following example to display the calendar time:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NUL);
printf ("The Calendar Time is%d
", LT);
return 0;
}
The result of the operation was related to the time, and the result I was running was:
The Calendar time is 1122707619
1122707619 is the calendar time when I run the program. This is the number of seconds from January 1, 1970 0:0 to 0 seconds.
4.2 Getting the date and time
The date and time mentioned here are the information of the year, month, day, hour, minute and second that we usually say. From the 2nd section we already know that this information is stored in a struct called a TM, so how do you save a calendar time as an object of a TM structure?
The functions that can be used are gmtime () and localtime (), and the prototypes of these two functions are:
struct TM * gmtime (const time_t *timer);
struct TM * localtime (const time_t * timer);
The Gmtime () function converts the calendar time to world standard Time (that is, GMT) and returns a TM structure to hold the time, while the localtime () function converts the calendar time to local time. For example, the world standard Time now obtained with the gmtime () function is July 30, 2005 7:18 20 seconds, then the local time I get in China using the localtime () function will be 8 hours later than the world standard Time, i.e. July 30, 2005 15:18 20 seconds. Here's an example:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *local;
time_t T;
T=time (NUL);
Local=localtime (&t);
printf ("Local hour is:%d
", Local->tm_hour);
Local=gmtime (&t);
printf ("UTC hour is:%d
", Local->tm_hour);
return 0;
}
The operating result is:
Local Hour is:15
UTC Hour Is:7
4.3 Fixed time format
We can display the time in a fixed format through the Asctime () function and the CTime () function, both of which are char* strings. The time format returned is:
Day of the week month Date: minute: Second year
/
For example: Wed Jan 02 02:03:55 1980
/
which
is a newline character, which is a null char that indicates the end of the string. The following is a prototype of two functions:
char * asctime (const struct TM * timeptr);
char * CTime (const time_t *timer);
where the asctime () function generates a string with a fixed-format save time information through a TM structure, and CTime () generates a time string through the calendar time. In this case, the asctime () function simply fills the fields of the TM structure object into the corresponding position of the time string, and the CTime () function needs to refer to the local time setting, convert the calendar time to local time, and then generate the formatted string. Below, if T is a non-empty time_t variable, then:
printf (CTime (&t));
Equivalent to:
struct TM *ptr;
Ptr=localtime (&t);
printf (Asctime (PTR));
So, the result of the two printf statements output from the following program is different (unless you set the local time zone to the time zone where world standard Time is located):
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Lt =time (NUL);
Ptr=gmtime (<);
printf (Asctime (PTR));
printf (CTime (<));
return 0;
}
Operation Result:
Sat Jul 30 08:43:03 2005
Sat Jul 30 16:43:03 2005
4.4 Custom Time format
We can use the strftime () function to format the time as we want. Its prototype is as follows:
size_t strftime (
Char *strdest,
size_t MaxSize,
const Char *format,
Const struct TM *timeptr
);
We can place the time information stored in the timeptr in the string pointed to by the strdest, with a maximum of maxsize characters in the strdest, according to format commands in format point to String. The function returns the number of characters placed in the string pointed to by strdest.
The function strftime () operates somewhat like sprintf (): Identifies a collection of formatting commands that begin with a percent sign (%), and the formatted output is placed in a string. The format command describes the exact representation of the various date and time information in the string strdest. Other characters in the format string are placed in the string as is. The format commands are listed below, and they are case-sensitive.
%a shorthand for the day of the week
%A full name of the week
%b of the Month
Full name of the%B month
Time string for the date of%c standard
After two digits of the%c year
The day ordinal of a month in%d decimal notation
%d Month/day/year
%e the day ordinal of a month in a two-character field, in decimal notation
%F year-month-day
%g two digits of the year, using week-based
%G years, using week-based years
%h Abbreviated month name
%H 24-Hour Hour
%I 12-Hour Hour
%j decimal indicates the day ordinal of the year
%m the month represented by decimal
%M minutes in a 10 o'clock-hour representation
%n New Line character
%p equivalent display of the local AM or PM
%r 12 hours of time
%R display hours and minutes: hh:mm
%s number of seconds in decimal
%t Horizontal Tab
%T display time seconds: hh:mm:ss
%u days of the week, Monday for the first day (values from 0 to 6, Monday to 0)
%u year of the week, the Sunday as the first day (value from 0 to 53)
%V Week of the year, using week-based
%w Decimal Day of the week (value from 0 to 6, Sunday is 0)
%W Week of the year, Monday as the first day (value from 0 to 53)
Date string for%x standard
Time string for%x standard
%y decimal Year without century (values from 0 to 99)
%Y decimal year with century part
%z,%z the time zone name and returns a null character if the time zone name cannot be obtained.
Percent hundred percent semicolon
If you want to show what time it is now and display it as a 12-hour system, just like this procedure:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Char str[80];
Lt=time (NUL);
Ptr=localtime (<);
Strftime (str,100, "It's now%I%p", PTR);
printf (str);
return 0;
}
The result of this operation is:
It's now 4PM
The following program displays the current full date:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include
#include
void Main (void)
{
struct TM *newtime;
Char tmpbuf[128];
time_t LT1;
Time (<1);
Newtime=localtime (<1);
Strftime (Tmpbuf, $, "Today is%A, day%d of%B in the year%Y.
", newtime);
printf (TMPBUF);
}
Operation Result:
Today is Saturday, Day's July in the year 2005.
4.5 Calculating the length of duration
Sometimes in the actual application to calculate the duration of an event, such as the calculation of typing speed. In the 1th section of the timing section, I've used the clock function to give an example. The Clock () function can be accurate to the millisecond level. Also, we can use the Difftime () function, but it is only accurate to seconds. The function is defined as follows:
Double Difftime (time_t time1, time_t TIME0);
Although the time interval returned in seconds by the function is double, this does not mean that the time has the same precision as a double, which is what its arguments think (time_t is calculated in seconds). For example, the following procedure:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "time.h"
#include "stdio.h"
#include "Stdlib.h"
int main (void)
{
time_t start,end;
Start = time (NUL);
System ("pause");
End = Time (NUL);
printf ("The pause used%f seconds.
", Difftime (End,start));//<-
System ("pause");
return 0;
}
The result of the operation is:
Please press any key to continue ...
The pause used 2.000000 seconds.
Please press any key to continue ...
It can be imagined that the pause time is not so coincidence that it is a full 2 seconds. In fact, you replace the one line with the "//<-" comment in the above program with the following line of code:
printf ("The pause used%f seconds.
", End-start);
The result is the same.
4.6 Decomposition time converted to calendar time
The decomposition time is the time structure saved by year, month, day, hour, minute, second and so on, which is the TM structure. We can use the Mktime () function to convert the time represented by the TM structure into a calendar time. Its function prototype is as follows:
time_t mktime (struct TM * timeptr);
The return value is the converted calendar time. So that we can set a decomposition time, and then the time to operate, the following example can be calculated July 1, 1997 is the day of the week:
CODE: [Copy to Clipboard]
--------------------------------------------------------------------------------
#include "time.h"
#include "stdio.h"
#include "Stdlib.h"
int main (void)
{
struct TM T;
time_t T_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 (&t);
printf (CTime (&t_of_day));
return 0;
}
Operation Result:
Tue Jul 01 00:00:01 1997
Now notice that with the Mktime () function, is it possible for us to manipulate any time before now? Can you figure out August 15, 1945 is the day of the week? The answer is in the negative. Because this time is before January 1, 1970, so in most compilers, such a program can be compiled through, but the runtime will be abnormally terminated.
5. Summarize
This article introduces the concepts of date and time in standard C/C + + and describes how these functions and data structures are used in a variety of instances. I think that some concepts related to time are quite important, and understanding these concepts is the basis for understanding the transformations of various time formats, and the basis of applying these functions and data structures.
Reference documents
[1] Standard C + + programming tutorial, Electronic industry Press, 2003.
[2] MSDN Library, Microsoft corporation,2003.
----------------
Transfer from http://hi.baidu.com/im_ds/blog/item/f5b10f39177e1df93a87ce88.html
[Reprint] How to get the date and time in C + +