Linuxunix-time timestamp processing conversion function

Source: Internet
Author: User
Tags cst time time zones set time string format time and date


Linux/unix-time timestamp processing conversion function


The time function under Linux
We can often use time in programming, such as getting the system time (to get the system's year, month, day, hour, minute, second, week, etc.), or to do something at intervals, then we use some time functions.

There are two common ways to store storage time under Linux:
One is from 1970 to now after how many seconds;
One is to use a structure to store the date and time of each month and seconds.

time_t This type is used to store the number of seconds from 1970 to now, to be more precise, you can use structural struct timeval, which is precise to subtle.
struct Timeval
{
Long tv_sec; /* sec */
Long tv_usec; /* microseconds */
};

and the direct storage date is a structure:
struct TM
{
int tm_sec; /* seconds, normal range 0-59, but allowed to 61*/
int tm_min; /* min, 0-59*/
int tm_hour; /* hours, 0-23*/
int tm_mday; /* Day, that is, the first day of the one months, 1-31*/
int Tm_mon; /* month, starting from January, 0-11*/
int tm_year; /* years, from 1900 to now how many years * *
int tm_wday; /* Week, Day of the week, starting from Sunday, 0-6*/
int tm_yday; /* FROM January 1 this year to the current number of days, range 0-365*/
int tm_isdst; /* Daylight Saving Time Flag * *
};
It is important to note that the year is the year since 1900, and not directly stored like 2008, the month starting from 0, 0 for January, the week is starting from 0, 0 for Sunday, and 1 for Monday.


Here's a look at our usual time functions:
#include <time.h>

Char *asctime (const struct tm* timeptr);
The time that the information in the structure is converted to real-world, displayed as a string;

Char *ctime (const time_t *TIMEP);
Convert TIMEP to Real world time, with string display, it differs from asctime in that the Parameter form is different;

Double Difftime (time_t time1, time_t time2);
Returns the number of seconds in a two-time difference;

int gettimeofday (struct timeval *tv, struct timezone *tz);
Returns the number of seconds and subtleties of the current distance of 1970, followed by the TZ is the time zone, generally not used;

struct tm* gmtime (const time_t *TIMEP);
Converting the time represented by time_t to UTC time without time zone conversion is a struct TM structure pointer;

Stuct tm* localtime (const time_t *TIMEP);
Similar to Gmtime, but it is time-zone-converted.

time_t mktime (struct tm* timeptr);
Converts the time of the struct TM structure to the number of seconds from 1970 to the present;

time_t time (time_t *t);
Gets the number of seconds since January 1, 1970.


The above is a simple introduction, following the actual combat to see the use of these functions:
Download: gettime1.c
1/*gettime1.c*/
2#include <time.h>
3int Main ()
4{
5time_t TIMEP;
6time (&AMP;TIMEP); /* Get the current time for the time_t type */
7/* use Gmtime to convert the time of the time_t type to the time press of the struct TM type,
8 then use Asctime to convert to our common format Fri Jan 11 17:25:24 2008
9*/
10printf ("%s", Asctime (Gmtime (&AMP;TIMEP)));
11return 0;
12}
Compile and run:
$GCC-O gettime1 gettime1.c
$./gettime1
Fri Jan 11 17:04:08 2008

The following is a direct conversion of the time_t type to our common format:
Download: gettime2.c
13/* gettime2.c*/
14#include <time.h>
15int Main ()
16{
17time_t TIMEP;
18time (&AMP;TIMEP); /* Get time_t type current time */
19/* converted to a common string: Fri Jan 11 17:04:08 2008*/
20printf ("%s", CTime (&AMP;TIMEP));
21return 0;
22}
Compile and run:
$GCC-O gettime2 gettime2.c
$./gettime2
Sat Jan 12 01:25:29 2008

I read a book that said these two examples if executed successively, two results in addition to the second difference (the execution of the program takes time), should be the same, but I do here but found a long time to press, one is Friday, one is Saturday, and then I executed it with the date command
$date
61 Month 01:25:19 CST 2008
I found that date and gettime2 are more consistent, and I estimate that gettime1 may not have been converted by time zones, and they are different.
Download: gettime3.c
23/*GETTIME3.C * *
24#include <time.h>
25int Main ()
16X
27char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
28time_t TIMEP;
29struct TM *p;
30time (&AMP;TIMEP); /* Time to get the time_t structure, UTC time */
31p = Gmtime (&AMP;TIMEP); /* UTC time converted to struct TM structure */
32printf ("%d/%d/%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday);
33printf ("%s%d:%d:%d/n", Wday[p->tm_wday], P->tm_hour,
34p->tm_min, p->tm_sec);
35return 0;
36}
Compile and run:
$GCC-O gettime3 gettime3.c
$./gettime3
2008/1/11 Fri 17:42:54

Judging from this time, it is consistent with the gettime1.
Download: gettime4.c
37/*gettime4.c*/
38#include <time.h>
39int Main ()
40{
41char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
42time_t TIMEP;
43struct TM *p;
44time (&AMP;TIMEP); /* Time to get the time_t structure, UTC time */
45p = localtime (&AMP;TIMEP); /* local time converted to struct TM structure */
46printf ("%d/%d/%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday);
47printf ("%s%d:%d:%d/n", Wday[p->tm_wday], P->tm_hour, P->tm_min, p->tm_sec);
48return 0;
49}
Compile and run:
$GCC-O gettime4 gettime4.c
$./gettime4
2008/1/12 Sat 1:49:29

From the above results we can say:
Time, Gmtime, and Asctime are represented by UTC time, except for the data type, and
LocalTime, the time that CTime represents is the time after the time zone is converted, and it should be consistent with the CST time that you represent with the system command date.
Download: gettime5.c
50/*gettime5.c*/
51#include <time.h>
52int Main ()
53{
54time_t TIMEP;
55struct TM *p;
56time (&AMP;TIMEP); /* Current time_t type UTC time */
57printf ("Time ():%d/n", TIMEP);
58p = LocalTime (&AMP;TIMEP); /* Convert to local TM structure time by */
59TIMEP = Mktime (p); /* Convert to UTC time of type time_t, there is a time zone conversion */
60printf ("Time ()->localtime ()->mktime ():%d/n", TIMEP);
61return 0;
62}
Compile and run:
$GCC-O gettime5 gettime5.c
$./gettime5
Time (): 1200074913
Time ()->localtime ()->mktime (): 1200074913

This translates the UTC time into local time, and then converts the local time to UTC time, and the result of their conversion remains the same.
Download: gettime6.c
63/*GETTIME6.C * *
64#include <time.h>
65int Main ()
66{
67time_t TIMEP;
68struct TM *p;
69time (&AMP;TIMEP); /* Get the time_t type of UTC time */
70printf ("Time ():%d/n", TIMEP);
71p = Gmtime (&AMP;TIMEP); /* UTC time to get the TM structure */
72TIMEP = Mktime (p); /* conversion, there will be a time zone conversion */
73printf ("Time ()->gmtime ()->mktime ():%d/n", TIMEP);
74return 0;
953
Compile and run:
$GCC-O gettime6 gettime6.c
$./gettime6
Time (): 1200075192
Time ()->gmtime ()->mktime (): 1200046392
From here we can see that after the conversion time is inconsistent, calculated, a full 8 hours ((1200075192-1200046392)/3600 = 8), indicating that Mktime will convert the local time to UTC time, which is originally UTC time, Then make a time zone conversion, the result is 8 hours, should pay attention when using.





Function Classification:
1. Set time: Settimeofday, Tzset
2. Time of acquisition: Ftime, Gettimeofday
3. Time format conversion: Mktime, strftime; Gmtime, localtime; Asctime, CTime
4. Other: Clock, difftime


Asctime: The time and date are expressed in string format
Header file: time.h
function definition: char *asctime (const struct TM *timeptr);
Description: Asctime () Converts the information in the TM structure referred to by the function timeptr to the time-date representation used in the real world, and then returns the result in string form. This function has been converted from time zone to local time, and the returned string format is: "Wed June 21:49:08 1993/n"

CTime: The time and date are expressed in string format
Header file: time.h
function definition: char *ctime (const time_t *TIMEP);
Description: CTime () with the Asctime () function, just the input parameter is time_t.
Application Examples:
#include <stdio.h>
#include <time.h>
int main (void)
{
time_t TIMEP;
Time (&AMP;TIMEP);
printf ("%s", CTime (&AMP;TIMEP));
printf ("%s", Asctime (Gmtime (&AMP;TIMEP)));
return 0;
}
Operation Result:
Sun Dec 14 15:30:11 2008
Sun Dec 14 15:30:11 2008


Clock: Gets the approximate time that the process consumes the CPU
Header file: time.h
function definition: clock_t clock (void);
Description: Clock () is used to return the approximate time that the process consumes the CPU.

Difftime: Calculating Time gaps
Header file: time.h
function definition: Double difftime (time_t time1, time_t TIME0);
Note: Difftime () is used to calculate the parameter TIME1-TIME0, and the result is returned with the exact value of type double. The time of two parameters is the UTC time, which is calculated from January 1, 1970 0:0 0 seconds.

Ftime: Get the current time and date
Header file: sys/timeb.h
function definition: int ftime (struct timeb *tp);
Description: Ftime () outputs the date of the day from the structure referred to by the parameter TP. The TP structure is defined as follows:
struct timeb{
/* is the number of seconds since January 1, 1970 */
time_t time;
/* for 1 per thousand seconds */
unsigned short millitm;
/* Time difference between the current time zone and Greenwich, in units per unit */
Short timezone;
/* For daylight saving time correction status, unless 0 is the daylight Saving time correction */
Short Dstflag;
};
Returns 0 regardless of success or failure.
Application Examples:
#include <stdio.h>
#include <sys/timeb.h>
int main (void)
{
struct TIMEB tp;
Ftime (&AMP;TP);
printf ("Time:%d/n", tp.time);
printf ("Millitm:%d/n", TP.MILLITM);
printf ("TimeZone:%d/n", Tp.timezone);
printf ("Dstflag:%d/n", Tp.dstflag);
return 0;
}
Operation Result:
time:1229271908
millitm:716
TimeZone:-480
dstflag:0

Gettimeofday: Get the current time
Header files: sys/time.h unist.d
function definition: int gettimeofday (struct timeval *tv, struct timezone *tz);
Note: Gettimeofday () returns the current time in the structure referred to by TV, and the local time zone information is placed in the structure referred to by TZ. The success returns 0, the failure returns 1, and the error code is stored in errno. Efault is the memory space referred to by the pointer TV and TZ to exceed the access rights.
The TIMEVAL structure is defined as:
struct timeval{
/* is the number of seconds since January 1, 1970 */
Long tv_sec;
/* microseconds */
Long tv_usec;
};
The timezone structure is defined as:
struct timezone{
/* and Greenwich TIME DIFFERENCE how many minutes */
int tz_minuteswest;
/* Daylight Saving Time status */
int tz_dsttime;
};
Both of these structures are defined in/usr/include/sys/time.h, and tz_dsttime represent the following states:
Dst_none/* Do not use */
DST_USA/* USA */
Dst_aust/* Australia */
Dst_wet/* Western Europe *
Dst_met/* Central Europe *
Dst_eet/* Eastern Europe *
Dst_can/* Canada */
DST_GB/* Britannia */
Dst_rum/* Romania */
Dst_tur/* Turkey * *
Dst_austalt/* Australia (after 1986) */

Gmtime: Converts the number of seconds to the current time and date
Header file: time.h
function definition: struct TM *gmtime (const time_t *TIMEP);
Description: Gmtime () 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.
The structure TM is defined as:
struct tm{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int Tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
Parameter description:
The int tm_sec represents the current number of seconds, the normal range is 0-59, but is allowed to 61 seconds
int Tm_min represents current score, range 0-59
int Tm_hour The number of hours from midnight, with a range of 0-23
int Tm_mday The number of days in the current month, range 01-31
The 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 of the week, starting from Monday, with a range of 0-6
int Tm_yday The number of days since January 1 this year, ranging from 0-365
int TM_ISDST Daylight Saving time flag
The time date returned by this function is not converted from time zone, which is UTC time.

LocalTime: Converts the number of seconds to local current time and date
Header file: time.h
function definition: struct *localtime (const time_t *TIMEP);
Description: LocalTime () 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. Please refer to Gmtime () for the definition of structure TM. The time date returned by this function has been converted to the local time zone.

Mktime: Converting time structure data to elapsed seconds
Header file: time.h
function definition: time_t mktime (struct TM *timeptr);
Description: Mktime () is used to convert the TM structure data referred to by the parameter timeptr to the number of seconds elapsed since the UTC time of January 1, 1970 0:0 0 seconds. Returns the number of seconds elapsed.

Settimeofday: Set the current time
Header files: sys/time.h unistd.h
function definition: Settimeofday () sets the current time to the structure information referred to by TV, and the local time zone information is set to the structure referred to by TZ. Please refer to Gettimeofday () for detailed instructions. Note that only root permissions can be used to modify the time of this function. The success returns 0, the failure returns 1, and the error code is stored in errno.
Error code:
Eperm does not call Settimeofday () with root permission, not enough permissions
EINVAL time zone or some data is incorrect and cannot be set correctly

Strftime: Formatting dates and times
Header file: time.h
Function definitions: size_t strftime (char *s, size_t max, const char *format, const struct TM *TM);
Note: strftime () Converts the time structure of the parameter tm to the string format specified by the parameter format, and the converted string content is copied to the string array referred to in parameter S, and the maximum length of the string is controlled by the parameter max.
Here is the format directive for the parameter format:
%a name abbreviations for the local Sunday period, such as: Sun
%A name abbreviations for the local Sunday period, such as: Sunday
%b abbreviation for local month
%B the full name of the local month
Local appropriate date and time notation for%c
%c represents the year in year/100
The number of days in%d months, represented by 01-31
%d Equivalent to "%m%d%y" format
The number of days in the%e month, represented by 1-31
%h abbreviation for local month
%H represents hours in 24-hour notation for 00-23
%I Represents hours in 12-hour notation for 01-12
%j days in the year (001-366)
%k represents hours in 24-hour notation for 0-23
%l represents hours in 12-hour notation for 1-12
%m Month (01-12)
%M minutes (00-59)
%n and/N
%p display the corresponding AM or PM
%P display the corresponding AM or PM
%r equivalent to using the "%i:%m:%s%p" format
%R equivalent to using the "%h:%m" format
%s The number of seconds elapsed since the UTC time from January 1, 1970 0:0 0 seconds
%s seconds (00-59)
%t with/t
%T 24 hour time, equivalent to "%h:%m:%s" format
%u Sunday of the week, Range 1-7, Monday starting from 1
%u Week of the Year (00-53), January the first Sunday starts at 01
%w Sunday of the week, Range 0-6, Sunday starting from 0
%W Week of the Year (00-53), January the first Monday starts at 01
%x Local appropriate date indication
%x local appropriate time to indicate
%y year in First century represents
%Y Full A.D. Year representation
Time zone name used by%Z
Percent '% ' sign
Returns the total number of characters copied to the string array referred to in argument s, excluding the string terminator. If 0 is returned, the string is not copied inside the parameter s, but does not indicate that there must be an error.
Additional NOTES: Environment variables TZ and tc_time affect this function result.
Application Examples:
#include <stdio.h>
#include <time.h>
int main (void)
{
Char *format[] = {"%I:%M:%s%p%m/%d%a", "%x%x%Y", NULL};
Char buf[30];
int i;
time_t clock;
struct TM *tm;
Time (&clock);
TM = LocalTime (&clock);
for (i = 0; Format[i]! = NULL; i++)
{
Strftime (buf, sizeof (BUF), Format[i], TM);
printf ("%s =%s/n", Format[i], buf);
}
return 0;
}
Operation Result:
%I:%M:%s%p%m/%d%a = 01:46:44 AM 12/15 Mon
%x%x%Y = 12/15/08 01:46:44 2008


Time: Get the current date
Header file: time.h
function definition: time_t time (time_t *t);
Description: Time () returns the number of seconds elapsed from UTC from January 1, 1970 to 0 seconds from 0:0. If T is not a null pointer, this function also saves the return value to the memory referred to by the T-pointer. The success returns the number of seconds, and the failure returns the (TIME_T-1) value, which causes the error to exist in errno.

Tzset: Set the time zone to be converted
Header file: time.h
function definition: void tzset (void); extern Char *tzname[2];
Description: Tzset () is used to set the environment variable TZ to the global variable Tzname, which is the current local time zone from the environment variable. This function is called automatically by the time conversion function. If TZ is set, Tzname will find the closest local time zone according to/etc/localtime. If TZ is null or is not recognized, the UTC time zone is used. This function is always successful and initializes the Tzname.

Linuxunix-time timestamp processing conversion function

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.