The processing of time in C program--time library functions

Source: Internet
Author: User

Contains file:<sys/time.h> <time.h> One, in C language has time_t, TM, Timeval and several types of time
1, time_ttime_t is actually a long integer type, defined as: typedef long time_t; /* Time value */

2, Timeval

Timeval is a struct, defined in time.h as:
struct Timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* microseconds. */
};

Where Tv_sec is epoch (1970-1-1-:00) and the number of seconds to create the struct timeval, Tv_usec is the number of microseconds, which is a fraction of the seconds behind.

3. TM

A TM is a struct, defined as:

struct TM
{
int tm_sec;     /* Represents the current number of seconds, the normal range is 0-59, but allowed to 61 seconds */int tm_min;   /* represents current score, range 0-59*/int tm_hour;  /* Number of hours from midnight, range 0-23 */int tm_mday;   /* Number of days in the current month, range 01-31 */int tm_mon;   /* Represents the current month, starting from January, ranging from 0-11 */int tm_year;   /* Number of years since 1900 */int tm_wday; /* The number of days in a week, starting from Monday, with a range of 0-6.   */int tm_yday; /* days in year. [0-365] */
int tm_isdst; /* Daylight saving time flag DST. [ -1/0/1]*/};
second, the specific operation function
Time () functionPrototype: time_t time (time_t * timer) Feature:gets the current system time, the returned result is a time_t type, which is actually a large integer whose value represents the number of seconds from the cut (coordinated Universal time) January 1, 1970 00:00:00 (called The epoch Time of the UNIX system) to the current moment. Then call localtime to convert the cut time represented by time_t to local time (we are +8 zones, 8 hours more than cut) and turn into a struct TM type, each data member representing the date and time of the year and seconds. The program example 1:time function gets the calendar time.Calendar TimeIs the time 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.  #include <time.h> #include <stdio.h> #include <dos.h> int main (void) {time_t t; t = time (NULL);  printf ("The number of seconds since January 1, 1970 is%ld", t);  return 0; } Example 2: The//time function is also commonly used forRandom numbergeneration, using calendar time as the seed.  #include <stdio.h> #include <time.h> #include <stdlib.h> int main (void) {int i;  Srand ((unsigned) time (NULL));  printf ("Ten random numbers from 0 to 99\n\n");  for (i=0;i<10;i++) printf ("%d\n", Rand ()%100);  return 0; } Example 3: Use the time () function with other functions (such as: LocalTime, Gmtime, Asctime, CTime) toget current system timeor Standard time. #include <stdio.h> #include <stddef.h> #include <time.h> int main (void) {time_t timer;//time_t is lo  ng int type struct TM *tblock;  Timer = time (NULL);//This sentence can also be changed to time (&timer);  Tblock = LocalTime (&timer);  printf ("Local time is:%s\n", Asctime (Tblock));  return 0; }gmtime () functionPrototype: struct TM *gmtime (long *clock); Function: A function that converts a date and time to Greenwich (GMT) time. Converts the information in the time_t structure referred to by the parameter TIMEP to the time date representation used by the real world, and then returns the result from the Fabric TM.
Description: The time date returned by this function was not converted by the time zone, but UTC time. Return value: Returns the structure TM represents the current UTC time Program example
#include "stdio.h"
#include "time.h"
#include "Stdlib.h"
int main (void)
{
time_t T;
struct TM *gmt, *area;
Tzset (); /* Tzset () Set time zone */
T = time (NULL);
Area = localtime (&t);
printf ("Local Time is:%s", Asctime (area));
GMT = Gmtime (&t);
printf ("GMT is:%s", Asctime (GMT));
return 0;
}

localtime () function

function: Converts the number of seconds from 1970-1-1:00 to the current time system to the calendar time.

Description: The time that this function obtains for the TM structure is that it has been converted to local time in the time zone.

usage: struct TM *localtime (const time_t *clock);

return value: Returns a pointer to the TM structure. The TM structure is the amount of time defined in the time.h for each of the respective storage times (month, day, etc.)
Structure of the body.
Program Example 1:

#include <stdio.h>

#include <stddef.h>

#include <time.h>

int main (void)

{

time_t timer;//time_t is a long int type

struct TM *tblock;

timer = time (NULL);

Tblock = localtime (&timer);

printf ("Local time is:%s\n", Asctime (Tblock));

return 0;

}

Execution Result:

Local time Is:mon Feb 11:29:26

Program Example 2:

The above example uses the Asctime function, and the following example does not use this function to get the current time of the system.
It should be noted that the year plus 1900, the month plus 1.

#include <time.h>

#include <stdio.h>

int main ()

{

struct TM *t;

time_t tt;

Time (&TT);

T=localtime (&TT);

printf ("%4d%02d month%02d Day%02d:%02d:%02d\n",
T->TM_YEAR+1900,T->TM_MON+1,T->TM_MDAY,T->TM_HOUR,T->TM_MIN,T->TM_SEC);

return 0;

}

the difference between localtime () and Gmtime ():

the Gmtime () function functions like getting the current system time, except that the acquired time is not converted by the time zone.

The localtime function obtains the time of the TM structure, which has been converted to local time by the time zone. Localtime_r () and Gmtime_r () function
struct TM * gmtime_r(const time_t *TIMEP, struct TM *result);
struct TM * localtime_r(const time_t *TIMEP, struct TM *result);

The Gmtime_r () function is the same as this, but it can store the data in a user-provided structure. The Localtime_r () function is the same as this, but it can store the data in a user-provided structure. It does not need to set tzname.

The results are processed immediately after using gmtime and localtime, otherwise the contents of the returned pointer may be overwritten.
A good way to do this is to use Gmtime_r and Localtime_r, and because the user-allocated memory is used, the two functions are not error-prone.

asctime () function

  Function: convert date and time to corresponding string (abbreviated form:Mon Feb 11:29:26)

Usage: char *asctime (const struct TM *tblock);

CTime () function

Function: Converts the date and time to a string.(English shorthand form:Mon Feb 11:29:26)

Usage: char *ctime (const time_t *time);

Description: The difference between CTime and Asctime is that CTime is the time string generated by the calendar time,
The asctime is generated by the TM structure to generate the time string.

mktime () function
function: Converts the TM time structure data into elapsed seconds (Calendar time).   

prototype:time_t mktime (strcut TM * timeptr);.   

Description: Mktime () is used to convert the TM structure data referred to by the parameter timeptr to
The number of seconds elapsed from the UTC time since January 1, 1970 0:0 0 seconds.

return value: Returns the number of seconds elapsed.

difftime () function

function: Calculates the length of time interval, in seconds, and can only be accurate to seconds.

prototype: Double Difftime (time_t time1, time_t TIME0);

Note: Although the return value of the function is of type double, this does not mean that the interval has the same precision as a double.
This is determined by its parameters.

strftime () function

Function: Format the time, or: Format a time string. We can use the strftime () function to format the time as we want.

Prototype: size_t strftime (char *strdest,size_t maxsize,const char *format,const struct TM *timeptr);

Parameters: We can place the time information stored in timeptr in the string pointed to by the format command in the string, based on format.
Stores up to maxsize characters in strdest.

Return value: This function returns the number of characters placed in the string pointed to by strdest.

Similar to 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

Abbreviated%B 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 year, using week-based

%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, put 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 10 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

Tip: The same behavior as Gmstrftime (), the difference is that the return time is local time.

Reference

Http://wenku.baidu.com/view/bce42784bceb19e8b8f6ba31.html?from=rec&pos=0&weight=14&lastweight=6 &count=5

The processing of time in C program--time library functions

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.