Linux time-related operations 20170607

Source: Internet
Author: User
Tags local time month name set time sprintf string format time and date

First, the Linux common time correlation function

-asctime,ctime,getttimeofday,gmtime,localtime,mktime,settimeofday,time

Asctime: Converting dates to strings

CTime: Converts a number of seconds into a string

Gettimeofday: Gets the time and date based on the given number of seconds subtracted from January 1, 1970

Gmtime: Gets the time and date based on the given number of seconds subtracted from January 1, 1970

LocalTime: Gets the time and date of the local time zone according to the given number of seconds subtracted from January 1, 1970

Mktime: Converting time structure data to elapsed seconds

Settimeofday: Set the system time, only the root user can run

Time: This function returns the number of seconds from 0:0 to 0 seconds from UTC of January 1, 1970 of A.D.

1.asctime (the time and date are represented in string format)

Related functions

Time,ctime,gmtime,localtime

Table header File

#include <time.h>

Defining functions

char * asctime (const struct TM * timeptr);

Function description

Asctime () Converts the information in the TM structure referred to by the parameter timeptr to the time-date representation used by the real world, and then returns the result in string form. This function has been converted from time zone to local time, and the string format is: "Wed June 21:49:08 1993/n"

return value

If the associated time-date function is called again, the string may be corrupted. This function differs from CTime in that the parameters passed in are different structures.

Additional Instructions

Returns a string representing the current local time date.

Example

#include <time.h>

Main ()

{

time_t TIMEP;

Time (&TIMEP);

printf ("%s", Asctime (Gmtime (&TIMEP)));

}

Perform

Sat Oct 28 02:10:06 2000

 

2.ctime (the time and date are represented in string format)

Related functions

Time,asctime,gmtime,localtime

Table header File

#include <time.h>

Defining functions

Char *ctime (const time_t *TIMEP);

Function description

CTime () 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 in string form. This function has been converted from time zone to local time, and the string format is "Wed June 21:49:08 1993/n". If the associated time-date function is called again, the string may be corrupted.

return value

Returns a string representing the current local time date.

Example

#include <time.h>

Main ()

{

time_t TIMEP;

Time (&TIMEP);

printf ("%s", CTime (&TIMEP));

}

Perform

Sat Oct 28 10:12:05 2000

 

3.gettimeofday (get current time)

Related functions

Time,ctime,ftime,settimeofday

Table header File

#include <sys/time.h>

#include <unistd.h>

Defining functions

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

Function description

Gettimeofday () returns the current time with a structure referred to by TV, and the local time zone information is placed in the structure that TZ refers to.

The TIMEVAL structure is defined as:

struct timeval{

Long tv_sec; /* sec */

Long tv_usec; /* microseconds */

};

The timezone structure is defined as:

struct timezone{

int tz_minuteswest; /* and Greenwich TIME DIFFERENCE how many minutes */

int tz_dsttime; /* Daylight Saving Time status */

};

Both of these structures are defined in/usr/include/sys/time.h. The status represented by Tz_dsttime is 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 value

The success returns 0, the failure returns 1, and the error code is stored in errno. Additional instructions efault the memory space referred to by the pointer TV and TZ exceeds the access permission.

Example

#include <sys/time.h>

#include <unistd.h>

Main () {

struct Timeval TV;

struct timezone tz;

Gettimeofday (&TV, &tz);

printf ("TV_SEC; %d/n ", tv.tv_sec);

printf ("TV_USEC; %d/n ", tv.tv_usec);

printf ("Tz_minuteswest; %d/n ", tz.tz_minuteswest);

printf ("Tz_dsttime,%d/n", tz.tz_dsttime);

}

Perform

tv_sec:974857339

tv_usec:136996

tz_minuteswest:-540

tz_dsttime:0

 

4.gmtime (get current time and date)

Related functions

Time,asctime,ctime,localtime

Table header File

#include <time.h>

Defining functions

struct Tm*gmtime (const TIME_T*TIMEP);

Function 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;

};

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 by the time zone, but UTC time.

return value

Returns the structure TM representing the current UTC time

Example

#include <time.h>

Main () {

Char *wday[]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

time_t TIMEP;

struct TM *p;

Time (&TIMEP);

P=gmtime (&TIMEP);

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);

}

Perform

2000/10/28 Sat 8:15:38

 

5.localtime (local current time and date obtained)

Related functions

Time, Asctime, CTime, gmtime

Table header File

#include <time.h>

Defining functions

struct TM *localtime (const time_t * TIMEP);

Function 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.

return value

Returns the structure TM representing the current local time.

Example

#include <time.h>

Main () {

Char *wday[]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

time_t TIMEP;

struct TM *p;

Time (&TIMEP);

P=localtime (&TIMEP); /* Get local time */

printf ("%d%d%d", (1900+p->tm_year), (L+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);

}

Perform

2000/10/28 Sat 11:12:22

 

6.mktime (convert time structure data to elapsed seconds)

Related functions

Time,asctime,gmtime,localtime

Table header File

#include <time.h>

Defining functions

time_t mktime (Strcut TM * timeptr);

Function description

The 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.

return value

Returns the number of seconds elapsed.

Example

/* Take time (in seconds) using localtime ()

Convert to a struct TM and then use Mktine () to convert the struct TM to the original number of seconds */

#include <time.h>

Main ()

{

time_t TIMEP;

Strcut TM *p;

Time (&TIMEP);

printf ("Time ():%d/n", TIMEP);

P=localtime (&TIMEP);

TIMEP = Mktime (p);

printf ("Time ()->localtime ()->mktime ():%d/n", TIMEP);

}

Perform

Time (): 974943297

Time ()->localtime ()->mktime (): 974943297

 

7.settimeofday (set current time)

Related functions

Time,ctime,ftime,gettimeofday

Table header File

#include <sys/time.h>

#include <unistd.h>

Defining functions

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

Function description

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.

return value

The success returns 0, the failure returns 1, and the error code is stored in errno.

Error code

Eperm does not call Settimeofday () by root, and does not have sufficient permissions.

EINVAL time zone or some data is incorrect and cannot be set correctly.

 

8.time (get current time)

Related functions

Ctime,ftime,gettimeofday

Table header File

#include <time.h>

Defining functions

time_t time (time_t *t);

Function description

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

return value

Success returns the number of seconds, and failure returns the ((time_t)-1) value, which causes the error to exist in errno.

Example

#include <time.h>

Main ()

{

int seconds= time ((time_t*) NULL);

printf ("%d/n", seconds);

}

Perform

9.73E+08

The 9.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:

#i nclude "Time.h"

#i nclude "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

#nclude

void Main (void)

{

struct TM *newtime;

Char tmpbuf[128];

time_t LT1;

Time (<1);

Newtime=localtime (<1);

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

printf (TMPBUF);

}

Instance:

Ld_s32 setsystime (ld_s32 syssec)

{

struct Timeval tv_set;

Tv_set.tv_sec = syssec;

tv_set.tv_usec = 0;

if (Settimeofday (&tv_set,null) <0)

{

debugprintf ("Set Time to%d failed!\n", syssec);

return ld_failure;

}

Else

{

debugprintf ("Set Time to%d success!\n", syssec);

return ld_success;

}

}

Second, the use of NtpClient synchronization time

NtpClient

Options:

-C Count Stop after count count time (default = 0 means until forever)

-D Print Diagnostics (feature can be turned off at compile time)

The-G option causes the program to get more accurate results after ntpclient, not just (microseconds, default = 0 means until it is stopped forever)

-H Host name (IP address) (mandatory) NTP server, measured against system time

-I interval time check time every time (default value is 600)

-I attempts the server to use Adjtimex to lock the local clock (2)

-P port Name locks the local NTP client UDP port (default = 0 means "any available")

-Q Minimum Delay minutes minimum packet delay trade (default 800 microseconds)

-R in the standard input replay analysis code

-S simple clock setting (equivalent to-C 1)

-T Trust network and server, no RFC-4330 recommended check

Synchronization Time Example:

$ ntpclient-s-t-i 10-h 202.120.2.101

Instance:

sprintf (buf, "Ntpclient-o-s-c%d-i 15-h%s", count, Pntpsrv);

if (RUNSYSCMD2 (buf, buf, sizeof (BUF)))

{

debugprintf ("Run ntpclient command failed!\n");

return ld_failure;

}

Linux time-related operations 20170607

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.