You can use the localtime function to obtain the values of year, month, day, hour, minute, and second.
How to Implement C language for obtaining system time in Linux:
1. You can use the localtime function to obtain the values of year, month, day, hour, minute, and second respectively.
# Include <time. h> // header file of C Language
# Include <stdio. h> // I/O of C Language
Void main ()
{
Time_t now; // instantiate the time_t Structure
Struct tm * timenow; // instantiate the tm structure pointer
Time (& now );
// The time function reads the current time (International Standard time is not Beijing time), and then transmits the value to now
Timenow = localtime (& now );
// The localtime function converts the time now obtained from time to the time in your computer (that is, the region you set)
Printf ("Local time is % s \ n", asctime (timenow ));
// In the previous sentence, the asctime function converts the time into characters and outputs the time using the printf () function.
}
Note: time_t is a struct defined in time. h. The prototype of the tm struct is as follows:
Struct tm
{
Int tm_sec; // seconds 0-61
Int tm_min; // minutes 1-59
Int tm_hour; // hours 0-23
Int tm_mday; // day of the month 1-31
Int tm_mon; // months since jan 0-11
Int tm_year; // years from 1900
Int tm_wday; // days since Sunday, 0-6
Int tm_yday; // days since Jan 1, 0-365
Int tm_isdst; // Daylight Saving time indicator
};
2. For some requirements that require high accuracy, Linux provides gettimeofday ().
# Include <stdio. h>
# Include <stdlib. h>
# Include <sys/time. h>
Int main (int argc, char ** argv)
{
Struct tim start, stop, diff;
Gettimeofday (& start, 0 );
// Do what you want to do...
Gettimeofday (& stop, 0 );
Tim_subtract (& diff, & start, & stop );
Printf ("Total time: % d millisecond \ n", diff. TV _usec );
}
Int tim_subtract (struct tim * result, struct tim * x, struct tim * y)
{
Int nsec;
If (x-> TV _sec> y-> TV _sec)
Return-1;
If (x-> TV _sec = y-> TV _sec) & (x-> TV _usec> y-> TV _usec ))
Return-1;
Result-> TV _sec = (y-> TV _sec-x-> TV _sec );
Result-> TV _usec = (y-> TV _usec-x-> TV _usec );
If (result-> TV _usec <0)
{
Result-> TV _sec --;
Result-> maid + = 1000000;
}
Return 0;
}
- How to modify the system time in Linux Command Line Mode
- In Debian, the system time is eight hours faster than the normal time. A>
- DeviceMapper mechanism in Linux Kernel