Linux time and date

Source: Internet
Author: User
Tags time zones

Time and date

It is usually possible to determine the time and date pair Program It is very useful. The program may want to record its running time, or may need to change its running mode in some cases. For example, a game may refuse to run during working hours, or a scheduled backup program may want to wait until early morning to start an automatic backup. All UNIX systems use the same time and date
Start Point: Greenwich Mean Time (GMT), January 1, January 1, 1970 ). This is the starting point of the UNIX era, and Linux is no exception. In Linux
The number of seconds that have elapsed. This is similar to the MS-DOS processing time method, but the MS-DOS era began in 1980. Other systems use the start time of other epochs. Time is processed by a predefined time_t type. This is an integer that is large enough to accommodate the date and time calculated in seconds. In Linux, it is a long integer, which is defined in the header file time. h together with the time value processing function. Never assume that the time is 32 bits. In UNIX and Linux systems that use 32-bit time_t, the time will be rolled back on January 1, 2038. At that time, we hope that the system will start to use the time_t type larger than 32 bits. You can call the time function to obtain the underlying time value, which returns the number of seconds since the epoch. If tloc is not a null pointer, the time function also writes the returned value to the position pointed by the tloc pointer. Experiment: the simple program envtime. C below the time function demonstrates the usage of the time function: to run this program, it prints the underlying time value every two seconds within 20 seconds. The experiment parses this program to call the time function with a null pointer parameter, and returns the time and date calculated in seconds. After the program sleep for two seconds, it repeatedly calls the time function for a total of 10 calls. The time and date are expressed in seconds calculated from January 1, 1970, which is useful for measuring the duration of certain events.
. We can simply subtract the value of the two call times. However, ISO/ANSI
After careful consideration, the C Standards Committee did not specify the time_t type to measure the number of seconds between any time. They invented a function difftime, which is used to calculate two
The number of seconds between time_t values and returns it as a double type. The difftime function calculates the difference between two time values and returns the value of the time1-time2 as a floating point number. For Linux, the return value of the time function is the number of seconds, which can be processed. However, it is best to use difftime to maximize portability. To provide more meaningful time and date (for humans), we need to convert the time value to readable time and date. Some standard functions can help us do this. The gmtime function breaks down the underlying time value into a structure that contains some common fields. The TM structure is defined to contain at least the members shown in Table 4-2. Table 4-2
TM Member Description
Int tm_sec Seconds, 0 ~ 61
(Continued)
TM Member Description
Int tm_min Minute, 0 ~ 59
Int tm_hour Hour, 0 ~ 23
Int tm_mday Date in month, 1 ~ 31
Int tm_mon Month, 0 ~ 11 (0 in March)
Int tm_year Year from January 1, 1900
Int tm_wday Day of the week, 0 ~ 6 (Sunday is 0)
Int tm_yday Date in year, 0 ~ 365
Int tm_isdst Renewal or not
The tm_sec range can be a temporary leap second or a double leap second. Experiment: The program gmtime under the gmtime function. c uses the TM structure and gmtime function to print the current time and date: run this program. We get the time and date with obvious meaning: The experiment parser calls the time function to get the underlying time value, call gmtime to convert the value to
Structures of useful time and date values. The program uses printf to print the information. Strictly speaking, we should not use this method to print the original time value, because we cannot guarantee that it is
The value of the long type. Run the date command immediately after the gmtime program to compare their output. However, there is a small problem here. If you run this program in a time zone other than Greenwich Mean Time (GMT,
Or if you use a period in your location, you will find that the time (and possibly the date) is incorrect. Because gmtime returns time by GMT (now GMT is called the world standard time, or
UTC ). Linux and UNIX are used to synchronize all programs and systems around the world. Files created at the same time in different time zones will have the same creation time. Depending on the local time, we need
Use the localtime function. The localtime function is the same as the gmtime function, except that the values in the returned structure have been adjusted according to the local time zone and whether to use the timer. If you replace gmtime in the above program with localtime and then compile and run it again, you will see the correct time and date. To convert the decomposed TM structure to the original time_t time value, use the mktime function. If the TM structure cannot be expressed as a time_t value, mktime will return-1. To get a more "friendly" time and date representation, like the date command output, we can use the asctime function and ctime function: asctime function to return a string, the time and date given by the TM structure timeptr. The returned string is in a format similar to the following: it is always a fixed format with a length of 26 characters. The ctime function is equivalent to calling it with the original time value as the parameter and converting it to a readable local time. Experiment: The ctime function uses the following Code Let's take a look at the ctime function usage. Compile and run the ctime. C program, the output is as follows: Experiment Analysis ctime. C program calls the time function to get the underlying time value, so that ctime can do all the hard work, convert the time value into a readable string, and then print it. To have more control over the time and date string formats, the strftime function is provided in Linux and modern Unix-like systems. It is like a sprintf function for time and date, working in a similar way: the strftime function formats the time and date represented by the TM structure pointed by the timeptr pointer, and
Put the result in string S. The string must contain at least () maxsize characters. The format string is used to control the characters written into string S. Like printf, it contains
The common character of the string and the conversion controller used to format the time and date elements. The conversion controllers are shown in Table 4-3. Table 4-3
Conversion Controller Description Conversion Controller Description
% Abbreviation of day of the week % S Seconds, 00 ~ 61
% Full name of the day of the week % U Day of the week, 1 ~ 7 (Monday is 1)
% B abbreviation of month % u week of the year, 01 ~ 53 (Sunday is the first day of a week)
% B Full name of month % V Week of the Year, 01 ~ 53 (Monday is the first day of a week)
% C Date and Time % W Day of the week, 0 ~ 6 (Sunday is 0)
% D Date in month, 01 ~ 31 % X Date in local format
% H Hour, 00 ~ 23 % X Time in local format
% I 12-digit hour, 01 ~ 12 % Y Year minus 1900
% J Date in year, 001 ~ 366 % Y Year
% M Month in year, 01 ~ 12 % Z Time zone name
% M Minutes, 00 ~ 59 % Character %
% P A.m. (morning) or p.m. (afternoon)
Therefore, the normal date output by the date command is equivalent to the string in strftime format: To help read the date, we can use the strptime function, which takes a string representing the date and time as a parameter, create a TM structure that represents the same date and time: the format string is constructed in the same way as the strftime format string.
Strptime is similar to the sscanf function in string scanning. It also finds matching data fields and writes them to corresponding variables. Only the TM is filled based on the format string.
Structure member. However, the strptime conversion controller is slightly loose than the strftime controller, because the day of the week and the month in strptime can both be abbreviated and full names,
Both match the % A controller in strptime. In addition, strftime uses a number smaller than 10 to start with 0, while strptime regards it as optional. Strptime returns a pointer pointing to the character after the last character processed in the conversion process. If a character cannot be converted, the conversion process stops at this point. The caller needs to check whether enough content has been read from the passed string to ensure that meaningful values are written in the TM structure. Experiment: strftime function and strptime function Please note the conversion control character selected in the following program: Compile and run this program strftime. c. We get: The experiment parses the strftime program to get the current local time by calling time and localtime. However
It calls strftime with the appropriate format parameter to convert the time to a readable format. To demonstrate the usage of strptime, the program constructs a string containing the date and time.
Then, call strptime to break down the original time and date value and print it out. The conversion controller % R is the abbreviation of % H: % m in strptime. Note: To successfully scan the date, strptime requires an exact format string. This is very important. In general, this function does not precisely scan the date read from the user unless the format entered by the user is very strict. When strftime. C is compiled, you may see a warning message from the compiler. Because the GNU Library does not declare the strptime function by default. To solve this problem, add the following line before the statement that contains the time. h header file. The function of this line is to explicitly define the request's use of the X/Open Standard function:
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.