Application time_t of C + + time class

Source: Internet
Author: User
Tags cst time time zones local time month name

Unix Timestamp (Unix timestamp), or Unix time (Unix times), POSIX time, is a time representation defined as 1970 from Greenwich time The total number of seconds from January 01 00:00 00 seconds to now. Unix timestamps are used not only in UNIX systems, Unix-like systems, but also in many other operating systems.

A significant portion of the operating system is currently using 32-bit binary numbers to represent time. UNIX timestamps of such systems can be used up to Greenwich Mean time of January 19, 2038 03:14 07 seconds (binary:01111111 11111111 11111111 11111111). After a second, the binary number will change to 10000000 00000000 00000000 00000000, an overflow error, causing the system to misunderstand the time of December 13, 1901 20:45 52 seconds. This is likely to cause a software failure, or even a system crash. Systems that use 64-bit binary numbers to represent time (up to GMT 292,277,026,596, December 04, 15:30, 08 seconds) do not experience this kind of overflow.

First, let's look at the concepts of time and the difference between the concepts of time that need to be understood:
Local times (locale time)
GMT (Greenwich Mean TimeGMT
Time Coordination time (Universal times coordinatedUTC
local time, obviously, no explanation.
First look at the standard of time:
(1) UTC
The world is the earliest time standard. In 1884, 1s was determined internationally as the average daily length of 1/8.64x104 in the year. The time system formed by this standard, called the World, is UT1. International Atomic time scales began to be used internationally in 1972, and since then, the time after the prime meridian of the Greenwich Observatory was called the world, namely, UT2, or GMT (GMT), was the world of correction for periodic differences in Earth's rotational speed.
(2) Atomic time
In the 1967, the high-precision atomic clock was developed by using the characteristic of cesium atom oscillation cycle, and the time of 9,192,631,770 weeks of cesium atomic transition radiation was set to 1s. The time now used is the international atom, which was defined in October 1971, when it was compared by about 200 atomic clocks in the world, and then processed by the time of the International Bureau of Weights and Measures, the unified atom, referred to as the Tai.
(3) When the world is coordinated
time standard based on Earth rotation for world coordination  . Because the Earth's rotational speed is not uniform, not every day is a precise 86400 atom s, resulting in the rotation time and the world is 18 months between the existence of 1s error. In order to rectify this error, the International Earth Rotation Institute, according to the actual situation of Earth rotationGMTThe adjustment to increase or decrease the leap s, combined with the time of the International Bureau of Weights and measures to release standard Time to the world, this is called World Coordination (Utc:coordinatdeuniversaltime). UTC is expressed as a number in years (y), months (m), days (d), hours (h), minutes (min), seconds (s).

There are two kinds of time difference in GPS system, one is UTC, the other is LT (local time) is different from the time zone, UTC is the time of 0 time zone, local time, such as Beijing for the Morning Eight (East eight district),UTC Timeis 0 points, time is eight hours later than in Beijing, this calculation can be
From what we know above, we can think of Greenwich mean time as the coordinated Time (GMT=UTC),the GMT and UTC times are calculated in seconds.

Most of the time we see in the computer logs in our usual work isUTC TimeTo calculate, then how do weUTC TimeConverting to local time makes it easy to see the logs, so how do you convert the local time into a program developmentUTC TimeIt?
The following is a simple and easy-to-use tool that uses the Linux/unix command date to convert local time and native time.
As we all know, seen in the computerUTC TimeThe number of seconds is calculated from (January 01, 1970 0:00:00). What you see.UTC TimeThat's how many seconds it takes from this point in 1970 to the exact time.

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.

Linux storage time is common in two ways, one is from 1970 to now through the number of seconds, one is to use a structure to store the date and time of each other.
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 month, 1-31*/
int Tm_mon; /* month, starting from January, 0-11*/1+p->tm_mon;
int tm_year; /* years, from 1900 to now how many years */1900+ p->tm_year;
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 2011, 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);

Converts information in a structure to real-world time, as a string

Char *ctime (const time_t *TIMEP);

Convert TIMEP to True world time, shown in string, it differs from asctime in that the Parameter form passed in is different

Double Difftime (time_t time1, time_t time2);

Returns the number of seconds between two time differences

int gettimeofday (struct timeval *tv, struct timezone *tz);

Returns the number of seconds and subtleties of the current distance of 1970, and the following TZ is the time zone, typically not

struct tm* gmtime (const time_t *TIMEP);

Converts the time represented by time_t to UTC time without time zone conversion, which 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
/*gettime1.c*/
#include <time.h>

int main ()
{
time_t TIMEP;

Time (&AMP;TIMEP); /* Get the current time for the time_t type */
/* Use Gmtime to convert the time of the time_t type to the time of the struct TM type,//UTC time without time zone conversion
Then use Asctime to convert to our common format Fri Jan 11 17:25:24 2008
*/
printf ("%s", Asctime (Gmtime (&AMP;TIMEP)));
return 0;
}
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
/* gettime2.c*/
#include <time.h>

int main ()
{
time_t TIMEP;

Time (&AMP;TIMEP); /* Get time_t type current time */
/* Convert to a common string: Fri Jan 11 17:04:08 2008*/
printf ("%s", CTime (&AMP;TIMEP));
return 0;
}
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
/*GETTIME3.C * *
#include <time.h>

int main ()
{
Char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t TIMEP;
struct TM *p;

Time (&AMP;TIMEP); /* Time to get the time_t structure, UTC time */
p = gmtime (&AMP;TIMEP); /* UTC time converted to struct TM structure */
printf ("%d/%d/%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday);
printf ("%s%d:%d:%d\n", Wday[p->tm_wday], P->tm_hour,
P->tm_min, p->tm_sec);
return 0;
}
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
/*gettime4.c*/
#include <time.h>

int main ()
{
Char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t TIMEP;
struct TM *p;

Time (&AMP;TIMEP); /* Time to get the time_t structure, UTC time */
p = localtime (&AMP;TIMEP); /* local time converted to struct TM structure */
printf ("%d/%d/%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday);
printf ("%s%d:%d:%d\n", Wday[p->tm_wday], P->tm_hour, P->tm_min, p->tm_sec);
return 0;
}
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 all UTC time, except that the data type is different.

In the localtime, the time represented by CTime is the time after the time zone is converted, and it should be consistent with the CST time that you indicated with the system command date .

Download: gettime5.c
/*gettime5.c*/
#include <time.h>

int main ()
{
time_t TIMEP;
struct TM *p;

Time (&AMP;TIMEP); /* Current time_t type UTC time */
printf ("Time ():%d\n", TIMEP);
p = localtime (&AMP;TIMEP); /* Convert to local TM structure time by */
TIMEP = Mktime (p); /* Convert to UTC time of type time_t, there is a time zone conversion *///by LIZP error, no time zone conversion, convert the time of the struct TM structure to the number of seconds from 1970 to P
printf ("Time ()->localtime ()->mktime ():%d\n", TIMEP);
return 0;
}
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
/*GETTIME6.C * *
#include <time.h>

int main ()
{
time_t TIMEP;
struct TM *p;

Time (&AMP;TIMEP); /* Get the time_t type of UTC time */
printf ("Time ():%d\n", TIMEP);
p = gmtime (&AMP;TIMEP); /* UTC time to get the TM structure */
TIMEP = Mktime (p); /* conversion, there will be a time zone conversion *///by LIZP error, no time zone conversion, convert the time of the struct TM structure to the number of seconds from 1970 to P
printf ("Time ()->gmtime ()->mktime ():%d\n", TIMEP);
return 0;
}
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.

The strftime () function formats the time
We can use the strftime () function to format the time as we want. Its prototype is as follows:
size_t strftime (
Char *strdest,
size_t MaxSize,
const Char *format,
Const struct TM *timeptr
);
We can place the time information stored in the timeptr in the string pointed to by the strdest, with a maximum of maxsize characters in the strdest, according to format commands in format point to String. The function returns the number of characters placed in the string pointed to by strdest.
The function strftime () operates somewhat like 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
%b of the 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 years, using week-based years
%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, the 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
If you want to show what time it is now and display it as a 12-hour system, just like this procedure:
#include "time.h"
#include "stdio.h"
int main (void)
{
struct TM *ptr;
time_t lt;
Char str[80];
Lt=time (NULL);
Ptr=localtime (<);
Strftime (str,100, "It's now%I%p", PTR);
printf (str);
return 0;
}
The result of this operation is:
It's now 4PM
The following program displays the current full date:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main (void)
{
struct TM *newtime;
Char tmpbuf[128];
time_t LT1;

Time (&AMP;LT1);
Newtime=localtime (&AMP;LT1);

Strftime (Tmpbuf, "Today is%A, day%d of%B in the year%y.\n", NewTime);
printf (TMPBUF);

return 0;
}

Go to: http://www.cnblogs.com/iluzhiyong/archive/2014/01/24/3531996.html

Application time_t of C + + time class

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.