Linux time time zone, commonly used time function, shaping time calculation ideas

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


Linux time zone details and common time functions

time and time zone

The entire earth is divided into 24 time zones, each time zone has its own local time.

ø  UTC Time and GMT time

We can think of Greenwich Mean Time (GMT = UTC), GMT and UTC times in seconds. The

ø  UTC time and local time

UTC + time zone difference = local time

Time zone Chadong is positive, West is negative. Here, take the East eight zone time zone difference to +0800

UTC + (+0800) = local (Beijing) time

ø  UTC and Unix timestamp

See the computer in UTC time from (January 01, 1970 0:00:00) to start counting the seconds. The UTC time that you see is the number of seconds from the 1970 point of time to the exact time. The second number is the Unix timestamp.




Time (to get current)

Function Description:

#include <time.h>

time_t time (time_t *t);

This function returns the number of seconds elapsed from 0:0 UTC, January 1, 1970, from 0 seconds to the current time. If T is not a null pointer, this function also saves the return value to the memory referred to by the T pointer.

Return: Success returns the number of seconds, Failure returns ((time_t)-1) value, and the reason for the error is in errno.

Code Description:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main (int argc, char** argv)
{
int seconds = time (NULL);
printf ("%d\n", seconds);
return 0;
}



Execution results:

[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_time unixtime_time.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_time

1445008165



gmtime (get current time and date)

Function Description:

#include <time.h>

struct Tm*gmtime (const TIME_T*TIMEP);

Gmtime () Converts the information in the time_t structure of the parameter TIMEP to the time-date representation used in the real world, and then returns the result from the structure TM.
The definition of the structure TM is:
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;
};
int TM_SEC represents the current number of seconds, with a normal range of 0-59, but 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 of 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, the range is 0-6
int Tm_yday The number of days since January 1 this year, with a range of 0-365
int TM_ISDST flag for daylight saving time
The date returned by this function is not time zone conversion, but UTC time.

Back: Structure TM represents current UTC time



Code Description:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main (int argc, char** argv)
{
Const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t TIMEP;
struct tm* p;
Time (&AMP;TIMEP);
p = gmtime (&AMP;TIMEP);
printf ("Curday =%d-%d-%d\n", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);
printf ("Curweek =%s, Curtime =%d:%d:%d\n", Wday[p->tm_wday], P->tm_hour, P->tm_min, p->tm_sec);
return 0;
}



Results show:

[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_gmtime unixtime_gmtime.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_gmtime

Curday = 2015-10-16

Curweek = Fri, Curtime = 15:12:12

[Root@vm_174_171_centos unixtime]# Date-u

Fri Oct 15:12:13 UTC 2015

[Root@vm_174_171_centos unixtime]# Date

Fri Oct 23:12:16 CST 2015

[Root@vm_174_171_centos unixtime]# date-r #Print out time zone information here, Beijing is East eight district

Fri, OCT 2015 23:12:18 +0800

You can see that the date returned by Gmtime has not been converted by time zone, and here and date print exactly 8 hours (China time zone).



CTime (representing time and date in string format)

Function Description:

#include <time.h>

Char *ctime (const time_t *TIMEP);

CTime () Converts the information in the time_t structure of the argument TIMEP to the time-date representation used in the real world, and then returns the result as a string form. This string may be corrupted if the relevant time-date function is called again.

Code Description:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main (int argc, char** argv)
{
time_t TIMEP;
Time (&TIMEP);
printf ("%s", CTime (&TIMEP));
return 0;
}



Results show:

[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_ctime unixtime_ctime.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_ctime

Fri Oct 16 23:14:33 2015

[Root@vm_174_171_centos unixtime]# Date

Fri Oct 23:14:34 CST 2015



Asctime (representing time and date in string format)

Function Description:

#include <time.h>

char * asctime (const struct TM * timeptr);

Asctime () Converts the information in the TM structure referred to in the parameter timeptr to the time date representation method used in the real world, and then returns the result in string form. This string may be corrupted if the relevant time-date function is called again. This function differs from CTime in that the parameters passed in are different structures.

Code Description:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main (int argc, char** argv)
{
time_t TIMEP;
Time (&AMP;TIMEP);
printf ("%s", Asctime (Gmtime (&AMP;TIMEP));
}



Results show:
[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_asctime unixtime_asctime.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_asctime

Fri Oct 16 15:15:54 2015

[Root@vm_174_171_centos unixtime]# Date

Fri Oct 23:15:55 CST 2015

[Root@vm_174_171_centos unixtime]# Date-u

Fri Oct 15:15:57 UTC 2015

[Root@vm_174_171_centos unixtime]# Date-r

Fri, OCT 2015 23:16:01 +0800

Note that the time of the struct TM structure here is returned through gmtime and therefore does not pass the time zone conversion.


Gettimeofday (Get the current time)

Function Description:

#include <sys/time.h>
#include <unistd.h>

int gettimeofday (struct timeval * TV, struct timezone * tz)

Gettimeofday () returns the current time with the structure that the TV refers to, and the local time zone information is placed in the structure referred to by TZ.
The TIMEVAL structure is defined as:
struct Timeval {
Long tv_sec; /* SEC * *
Long tv_usec; /* microsecond * *
};
The timezone structure is defined as:
struct TimeZone {
int tz_minuteswest; /* and Greenwich TIME DIFFERENCE how many minutes * *
int tz_dsttime; * The state of Daylight saving time * *
};
Both of these structures are defined in the state represented by the/usr/include/sys/time.h,tz_dsttime as follows
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) * *

Return: Success returns 0, failure returns-1, error code is stored in errno.

Code Description:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

int main (int argc, char** argv)
{
struct Timeval TV;
struct timezone tz;
Gettimeofday (&AMP;TV, &tz);
printf ("tv_sec =%d, tv_usec =%d, Tz_minuteswest =%d, Tz_dsttime =%d\n",
Tv.tv_sec, Tv.tv_usec, Tz.tz_minuteswest, tz.tz_dsttime);

return 0;
}



Results show:

[Root@vm_174_centos unixtime]# g++-g-o unixtime_gettimeofday unixtime_gettimeofday.cpp

[Root@vm_174_centos unixtime]#./unixtime_gettimeofday

Tv_sec = 1445008619, tv_usec = 699804, tz_minuteswest = -480, Tz_dsttime = 0

[Root@vm_174_171_centos unixtime]# Date

Fri Oct 23:17:00 CST 2015

[Root@vm_174_171_centos unixtime]# Date-u

Fri Oct 15:17:02 UTC 2015

The time zone difference here is-480, which means GMT is 8 hours behind us (China time zone).


localtime (get local current time and date)

Function Description:

#include <time.h>

struct TM *localtime (const time_t * TIMEP);

LocalTime () Converts the information in the time_t structure of the parameter TIMEP to the time-date representation used in the real world, and then returns the result from the structure TM. Please refer to Gmtime () for the definition of structure TM. The time date returned by this function has been converted to a local time zone.

Code Description:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main (int argc, char** argv)
{
Const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t TIMEP;
struct tm* p;
Time (&AMP;TIMEP);
p = localtime (&AMP;TIMEP);
printf ("Curday =%d-%d-%d\n", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday);
printf ("Curweek =%s, Curtime =%d:%d:%d\n", Wday[p->tm_wday], P->tm_hour, P->tm_min, p->tm_sec);
return 0;
}



Results show:

[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_localtime unixtime_localtime.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_localtime

Curday = 2015-10-16

Curweek = Fri, Curtime = 23:23:37

[Root@vm_174_171_centos unixtime]#./unixtime_gmtime

Curday = 2015-10-16

Curweek = Fri, Curtime = 15:23:37

The results here are compared with the results of gmtime, we can see that gmtime gives GMT standard Time, LocalTime gives the local time according to time zone conversion (this is Beijing time, East eight, +0800).


Mktime (converts time structure data to elapsed seconds)

Function Description:

time_t mktime (Strcut TM * timeptr);

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 0 seconds from January 1, 1970 A.D.

Returns: Returns the number of seconds elapsed.

Code Description:


/*
* Use time () to obtain the Times (seconds), the use of localtime ()
* Convert to struct TM reuse Mktine () convert struct TM to original number of seconds
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main (int argc, char** argv)
{
time_t TIMEP;
struct tm* p;
Time (&AMP;TIMEP);
printf ("time () =%d\n", TIMEP);
p = localtime (&AMP;TIMEP);
TIMEP = Mktime (p);
printf ("Time ()->localtime ()->mktime ():%d\n", TIMEP);
return 0;
}



Results show:

[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_mktime unixtime_mktime.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_mktime

Time () = 1445010682

Time ()->localtime ()->mktime (): 1445010682
Settimeofday (set current time)

Function Description:

#include <sys/time.h>
#include <unistd.h>

int settimeofday (const struct timeval *tv,const struct timezone);

Settimeofday () Sets the current time to the structure information that the TV refers to, and the local time zone information is set to the structure referred to by the TZ. For detailed instructions please refer to gettimeofday (). Note that only the root permission can be used to modify the time.

Return: Success returns 0, failure returns-1, error code is stored in errno.

Eperm is not called Settimeofday () by root permission, and permissions are not sufficient.
Einval time zone or some data is incorrect and cannot be set correctly.



common calculation ideas based on the time of Linux shaping

This paper, based on the time of Linux shaping, gives some simplified calculation ideas, tries to enhance the reader's understanding of time processing from another angle, and hopes to help you.



Overview

In the development of background server, it is often necessary to compare and compute based on date and time. Similar functional requirements may include: Determine today is the day of the week, determine whether two times on the same date, whether in the same week, determine whether the current time in a specific period of day and so on. Although there is a system function localtime () can be very good to get date-related details, but because the information it gets is sufficiently detailed that the use of localtime () is actually an extra cost in some specific simple functions. For some simple judgments, we recommend a simpler, more primitive, easier to understand approach.




Calculation ideas

Under Unix/linux, the system time is expressed as a time_t type, which is essentially an integer value that begins with a reference point in history (GMT January 1, 1970 0 o'clock), and the number of seconds that lasts at the current moment. Under Linux, time_t is defined as a long type, which is a signed integral type.

Given China's different time zones from Greenwich, the starting point for China's time is eight O'Clock January 1, 1970 morning. For any time zone, the time_t representation rule can be represented by the following figure.


As above, T0 = 0, indicating the starting time, T1 is the T0, the first day of the 0-point time; T2 indicates the 0-point time of the second day; As you can see, for different time zones, the difference in the representation of the law is only T1 value. Starting from the T1 moment, the T1,T2,T3...,TN is a linear series with a tolerance of a day's time in seconds, which is recorded as D = 86400 (60*60*24).

For any one time, it can be expressed as:

t = T1 + kxd + M .... Formula 1

Where T1 is a time zone-dependent constant, M is the number of seconds in the day, and K can be understood as the number of days in history

After deformation can be obtained k = (t-t1-m)/D

Since M < D can be further simplified:

K = (t-t1)/D .... Formula 2

K is the day of the T moment, the number of days since T0.

For the moment T, the time of day 0:

TZ = T1 + (T-T1)/dxd .... Formula 3

TZ is 0 O ' time on the same day as T time.



Based on Formula 2 we can determine whether any two times t1,t2 is the same day, based on Formula 3 we can find out the time period T1 on the date. Based on these two formulas, we can also extend more date calculations related to the day, and it is easy to see that the calculation used by the formula is only an integer numeric operation.


For the calculation of the week, we can mimic the above ideas. The difference is that only T1 values are the starting time of the first week, such as the Monday morning 0, and the value of D is 604800 seconds per week (86400*7).

Through any moment T, we can find the current 0-point time, we can find the start of the week, and then through a simple comparison, it is easy to calculate the day of the week and some related extensions, this no longer one by one repeat.


Common function implementations

Gets the 0-point time value of the Tnow time, 0 points as the first second of the day

time_t gettodayzerotime (time_t tnow)

{

Return (((tNow-57600)/86400) *86400 + 57600);

}



Judge whether two time is on the same day, the concept of a 00:00:00 to 23:59:59

BOOL Isinsameday (time_t tTm1, time_t tTm2)

{

Return ((ttm1-57600)/86400 = = (ttm2-57600)/86400);

}



Gets the start time of the week of the Tnow, which is 0 points 0 minutes and 0 seconds of Monday this week.

Calculation of the idea, 1980-01-07 is Monday, this day 0 points of the plastic time is 316022400 (according to China time zone)

time_t getweekbegintime (time_t tnow)

{

Return ((tNow-316022400)/604800 * 604800 + 316022400);

}



Gets the end time of the week of the Tnow time, which is 23 59 minutes and 59 seconds of Sunday this week.

time_t getweekendtime (time_t tnow)

{

Return ((tNow-316022400)/604800 * 604800 + 316627199); 316022400 + 604800-1);

}



Determine whether two time is in the same week, the concept of a week for Monday from 00:00:00 to Sunday 23:59:59

BOOL Isinsameweek (time_t tTm1, time_t tTm2)

{

Return ((ttm1-316022400)/604800 = = (ttm2-316022400)/604800);

}

Code Explanation


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

time_t gettodayzerotime (time_t tnow)
{
Return (((tNow-57600)/86400) *86400 + 57600);
}

BOOL Isinsameday (time_t tTm1, time_t tTm2)
{
Return ((ttm1-57600)/86400 = = (ttm2-57600)/86400);
}

BOOL Isinsameweek (time_t tTm1, time_t tTm2)
{
Return ((ttm1-316022400)/604800 = = (ttm2-316022400)/604800);
}

time_t getweekbegintime (time_t tnow)
{
Return ((tNow-316022400)/604800 * 604800 + 316022400);
}

time_t getweekendtime (time_t tnow)
{
Return ((tNow-316022400)/604800 * 604800 + 316627199); 316022400 + 604800-1);
}

int main (int argc, char** argv)
{
time_t currtime, One_hour_after, One_day_after, One_week_after;
Time (&currtime);
One_hour_after = currtime + 3600; 1 hours later
One_day_after = Currtime + 86400; 1 days later
One_week_after = Currtime + 604800; 1 weeks later

printf ("Today's Zero Time ==>%d\n", Gettodayzerotime (Currtime));
printf ("Week Begin time ==>%d\n", Getweekbegintime (Currtime));
printf ("Week End time ==>%d\n", Getweekendtime (Currtime));
printf ("is in same day ==> (Currtime|one_hour_after =%d), (Currtime|one_day_after =%d) \ n",
Isinsameday (Currtime, One_hour_after), Isinsameday (Currtime, One_day_after));
printf ("is in same week ==> (Currtime|one_week_after =%d), (One_day_after|one_week_after =%d) \ n",
Isinsameweek (Currtime, One_week_after), Isinsameweek (One_day_after, One_week_after));

return 0;
}



Result Description

[Root@vm_174_171_centos unixtime]# g++-g-o unixtime_simplify unixtime_simplify.cpp

[Root@vm_174_171_centos unixtime]#./unixtime_simplify

Today zero Time ==> 1445097600

Week begin Time ==> 1444579200

Week End Time ==> 1445183999

is in same day ==> (Currtime|one_hour_after = 1), (currtime|one_day_after = 0)

is in same week ==> (currtime|one_week_after = 0), (one_day_after|one_week_after = 1)

[Root@vm_174_171_centos unixtime]# Date

Sun Oct 13:17:37 CST 2015

[Root@vm_174_171_centos unixtime]# date-d @1445097600

Sun Oct 00:00:00 CST 2015

[Root@vm_174_171_centos unixtime]# date-d @1444579200

Mon Oct 00:00:00 CST 2015

[Root@vm_174_171_centos unixtime]# date-d @1445183999

Sun Oct 23:59:59 CST 2015

Application Examples

In some activities, task logic, it is often necessary to have a value similar to the natural days, after a day, the value of zero.

For this kind of demand, we usually use [numerical, update time] to compare the time of the visit, and then clear zero. In accordance with the natural day Qing 0 rules For example, that is, in GetValue (), AddValue (), the value of the last update to determine the time t_upd, if Isinsameday (T_UPD, T_now) The current value is still valid, otherwise clear 0 value after the relevant operation. The T_UPD is updated to the current moment each time the value is modified.

Internationalization Considerations

For different time zones, the difference between the formulas is only the value of the T1, and the form and use of the formula does not need to change.

One way is to define the T1 macro, using different T1 values for versions of different time zones at the time of internationalization.

Alternatively, the T1 is defined as a global variable, and the system's LocalTime () function is used at server startup to properly initialize T1 by local time zone.





Rules that do not apply to year and month

Because of the number of days per year, the number of days per month is not fixed, so the calculation of this article does not apply to the monthly date of such a time point of judgment, based on past experience, a specific month specific date of the functional requirements is not very common, for these functions or use the localtime () function to facilitate some.


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.