The Method of Obtaining Current Time by time of NULL Function and localtime of under linux
- 2021-07-24 12:07:09
- OfStack
time (); Function
Function prototype: time_t time (time_t * timer)
Function: Get the calendar time of the machine or set the calendar time
Header file: time. h
Input parameters: timer=NULL, get the machine calendar time, = time value for setting calendar time;
time_t is a long type
/* time - Gets the current calendar time of the computer system (Calender Time)
* Functions that deal with date and time are all based on the return value of this function
*
* Function prototype:
* #include <time.h>
*
* time_t time(time_t *calptr);
*
* Return value:
* Success: Seconds, from 1970-1-1,00:00:00
*
* Use:
* time_t now;
*
* time(&now); // == now = time(NULL);
*/
localtime (); Function
Function prototype: struct tm * localtime (const time_t * timer)
Function purpose: Returns 1 machine time information expressed in tm structure
Header file: time. h
Input parameter: timer: Machine time obtained using the time () function;
/*
* localtime - Transform time values into local time , Taking into account the local time zone and daylight saving time flags
*
* Function declaration :
* #include <time.h>
*
* struct tm * localtime(const time_t *timer);
*
*/
// Structure tm Is defined as:
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 */
};
Since time_t is actually a long integer, what should I do if the number of seconds (that is, calendar time) from a time point (1 is generally 0: 00:0 on January 1, 1970) to that time exceeds the number that long integers can represent? For a value of the time_t data type, it cannot represent a time later than 19:14:07 on January 18, 2038. In order to be able to represent a longer time, some compiler vendors have introduced 64-bit or longer shaping numbers to save calendar time. For example, Microsoft uses the __time64_t data type in Visual C + + to save the calendar time, and obtains the calendar time through the _time64 () function (instead of using the time () function with 32-bit words), so that the time before 0:00:0 on January 1, 3001 (excluding this time point) can be saved through this data type.
/*
* time();
* @author Li Zheng <1244109467@qq.com>
*/
#include <time.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
struct tm *tp;
time_t t = time(NULL);
tp = localtime(&t);
printf("%d/%d/%d\n",tp->tm_mon+1,tp->tm_mday,tp->tm_year+1900);
printf("%d:%d:%d\n",tp->tm_hour,tp->tm_min,tp->tm_sec);
return 0;
}