The date and time in C ++

In C ++, to get the current system date and time, use the time function.

Declaration time function in time.h, which requires a parameter type is time_t type. We open time.h can see,

Time_t is just a so-called Long. Typedef Long time_t;

Declaration time function is as follows:

time_t  time( time_t *time )

When used, typically do not return values, but rather pass a parameter is passed as address, therefore, time argument function may change point in the function as:

* clock = new new time_t time_t;
Time (clock); // memory storage unit clock pointed to a "date and time" integer representation (called calendar time, calendar time).

At this time, the output clock, also do not understand also need to clock into a format that we have a good understanding of:

With ctime function ctime function prototype: char * ctime (const time_t * time);.

It is possible to get a string, char * s = ctime (clock); cout << s; e.g., the output of the VC I:

Thu Nov 12 13:30:04 2007

As follows: month, day, hour during the week of

Method 2:

Many times we do not need this format, we just want to get some of these values, such as year, month, date, etc., and then deal with their own, then you can use the localtime function

Function prototype:  struct (TM) * localtime (const time_t * Time);

It converts the calendar time to the local time, but the return value is a structure we take a look at the time.h:

struct tm
{
int tm_sec; /* Seconds: 0-59 (K&R says 0-61?) */
int tm_min; /* Minutes: 0-59 */
int tm_hour; /* Hours since midnight: 0-23 */
int tm_mday; /* Day of the month: 1-31 */
int tm_mon;  /* Months *since* january: 0-11 */
int tm_year; /* Years since 1900 */
int tm_wday; /* Days since Sunday (0-6) */
int tm_yday; /* Days since Jan. 1: 0-365 */
int tm_isdst; /* +1 Daylight Savings Time, 0 No DST, -1 don't know */
};
很简单, 其中要注意的是:

Week from Sunday start, namely: 0 for Sunday there is a tm_yday, expressed from January 1 to the number of days now, a range of values ​​from 0 to 365.

Years, from the 1900 count, and now digital, and in January start at zero so as to transform a little: Requirements for the current date

tm * mytime = new tm; // define a structure pointer, C ++ can not struct, but must be written in C language: struct (TM) * MyTime
time_t * = aclock new new time_t; // pointer time_t defined
time (clock); // calendar time obtained
mytime = localtime (aclock); // get the local time


int year=1900+mytime->tm_year;

int month=mytime->tm_mon+1;

int day=mytime->tm_mday;

......

If you want to get in front ctime format can asctime: i.e. asctime (mytime); returns a string

Namely: ctime corresponds asctime (localtime (tp));

 
Published 11 original articles · won praise 5 · views 20000 +

Guess you like

Origin blog.csdn.net/abigriver/article/details/1911913