Golang in time packet usage

Source: Internet
Author: User
Tags rfc822
This is a creation in Article, where the information may have evolved or changed.

Time package includes two types of times: Point in time (a moment) and often (a certain period of time)

1 time constants (time formatting)

Const (Ansic= "Mon Jan _2 15:04:05 2006"unixdate= "Mon Jan _2 15:04:05 MST 2006"rubydate= "Mon Jan 02 15:04:05-0700 2006"RFC822= "15:04 MST"rfc822z= "Jan 06 15:04-0700"//RFC822 with numeric zone    RFC850= "Monday, 02-jan-06 15:04:05 MST"RFC1123= "Mon, Jan 2006 15:04:05 MST"rfc1123z= "Mon, Jan 2006 15:04:05-0700"//RFC1123 with numeric zone    RFC3339= "2006-01-02t15:04:05z07:00"Rfc3339nano= "2006-01-02t15:04:05.999999999z07:00"Kitchen= "3:04pm"//Handy time stamps.    Stamp= "Jan _2 15:04:05"Stampmilli= "Jan _2 15:04:05.000"Stampmicro= "Jan _2 15:04:05.000000"Stampnano= "Jan _2 15:04:05.000000000")
These constants are some constants that are predefined for time formatting and temporal parsing, and they are all used for a specific period:
Mon Jan 2 15:04:05 MST 2006
This is Unix time 1136239445, because MST is GMT-0700, so this specified time can also be seen as

01/02 03:04:05pm ' 06-0700
Visible program apes also have a naughty side.

So all we have to do is use the time above to arbitrarily specify our own time format, for example:

Layout: = "01__02-2006 3.04.05 PM"

Fmt. Println (time. Now (). Format (layout))

It will output a similar time: 11__26-2014 8.40.00 PM


2 functions

Time consists of:

Time. Duration (length of time, consumption time)

Time. Time (dot)

Time. C (channel Channels) (Note: Time.c:=make (chan time). Time))


After function:

1) func after (d Duration) <-chan time

Indicates the amount of time, but does not block until the channel content is removed, and subsequent programs can continue to execute

2) Func sleep (d Duration) indicates how long the sleep is in a blocked state during hibernation and subsequent programs cannot execute.
Examples illustrate the difference:

Fmt. Println ("Hello")

Chan: = time. After (time. SECONE*1)

Fmt. PRINTLN ("World")

After executing the output Hello, the program then outputs world without waiting for 1s, but after 1s, chan has data, and Chan blocks

Mt. Println ("Hello")

Chan: = time. Sleep (time. SECONE*1)

Fmt. PRINTLN ("World")

Indicates that after the output of Hello, the program becomes dormant in 1s before the world is output. This shows that blocking and non-blocking are the essential differences between the two functions.

Because of the after feature, it is typically used to handle program timeout issues, as follows:

Select {Case m: = <-c:    handle (m) case <-time. After (5 * time. Minute):    FMT. Println ("Timed Out")}

3) Func Tick (d Duration) <-chan time
Time. Tick (time. Duration) usage and time. After almost, but it is a repeating process that indicates how much time is after, others are consistent with after


4) Type Duration Int64//time length, its corresponding time unit has Nanosecond,microsecond,millisecond,second,minute,hour

(1) Func parseduration (S string) (Duration, error)//incoming string, returns the time of the response, in which the valid time units in the passed-in string are as follows: H,m,s,ms,us,ns, the other units are invalid, If an invalid time unit is passed in, 0 is returned

(2) Func Since (t time) Duration//Indicates how long it has been since the T-moment, which is a period, which is equivalent to times. Now (). Sub (t)

(3) func (d Duration) Hours () float64//Convert the set time period to hour of the float64 type for output


(4) func (d Duration) Minutes () float64//Convert the set time period to Minutes of the float64 type for output


(5) Func (d Duration) nanoseconds () Int64//Convert the set time period to nanoseconds of the int64 type for output


(6) Func (d Duration) Seconds () float64//Convert the set time period to Seconds of the float64 type for output

(7) func (d Duration) string () string//vs. Parseduration function, which converts a time period to a string output


5) Type location
Func fixedzone (name string, offset int) *location
Func loadlocation (name string) (*location, error)
Func (L *location) string () string


6) Type month//defined for 1 years 12 months


Func (M Month) string () string//The time month is printed in string form. such as FMT. Println (time. June.string ()) prints out June


7) Type ParseError
Func (e *parseerror) Error () string
8) Type Ticker//is used primarily to invoke functions or evaluate expressions for a specified period of time, usually using go to open a co-use, which is a staccato
Func Newticker (d Duration) *ticker//Reborn into a Ticker, this Ticker contains a channel, which is sent at a given Duration time. Duration d must be greater than 0
Func (t *ticker) Stop ()//is used to close the corresponding Ticker, but does not close the channel

Examples are as follows:

Use time control to stop ticker

Ticker: = time. Newticker (Time.millisecond *)    go func () {for        t: = Range Ticker. C {            FMT. Println ("Tick at", T)        }    } () time. Sleep (Time.millisecond *)   //block, the number of times the execution is sleep time/ticker time    Ticker. Stop ()         FMT. Println ("Ticker stopped")

Stop ticker with channel control

Ticker: = time. Newticker (Time.millisecond *) c: = Make (chan int,num)//num The specified number of executions go func () {for t: = Range Ticker. C {             c<-1              fmt. Println ("Tick at", T)}} ()
Ticker. Stop ()
In this case, after executing the function num times in ticker time, the C channel is full and the corresponding function is no longer executed.

9) Type time//Includes date and times
Func Date (year int, month month, day, hour, Min, sec, nsec int, loc *location) time//After entering data in the specified format, the corresponding times are output in the format of
Yyyy-mm-dd Hh:mm:ss + nsec nanoseconds, where Loc must be specified, otherwise panic, examples are as follows: t: = time. Date (Time, time). November, 0, 0, 0, time. UTC) fmt. Printf ("Go launched at%s\n", t.local ()) output is:
Go launched at 2009-11-10 15:00:00-0800 PST

Func now () Time//returns the current times, including date, time, and timezone


Func Parse (layout, value string) (time, error)//input format layout and time string, output times


Func parseinlocation (layout, value string, loc *location) (Time, error)


Func Unix (sec int64, nsec Int64) time//return local times


Func (t) Add (d Duration) time//Increase


Func (t time) adddate (years int, months int, days int) time//Add date


Func (t) after (U time) bool//Determine if the timing t is behind the time U


Func (t time) before (U) BOOL//Determine if the timing t is in front of the time U


Func (t time) Clock () (Hour, min, sec int)//Get time t of Hour,min and second


Func (t time) Date () (year int, month month, day int)//Get time t of Year,month and days


Func (t time) day () int//Get time t


Func (T-time) Equal (U-time) bool//determine if T is the same as timing u


Func (t time) format (layout string) string//Time string formatting


Func (t *time) gobdecode (data []byte) error//code for God


Func (t time) Gobencode () ([]byte, error)//decoding God


Func (t time) Hour () int//Gets the hour of the time t


Func (t time) Isoweek () (year, week int)//Gets the years and weeks of the time t


Func (t time) in (Loc *location) time//gets the corresponding time of the LOC time zone t


Func (t time) Iszero () bool//Determine if the instance is 0 times January 1, Year 1, 00:00:00 UTC


Func (t time) local () time//Get local times


Func (t time) location () *location//Get local timezone


Func (t time) marshalbinary () ([]byte, error)//marshal binary serialization, which serializes the times T into the []byte array]


Func (T-time) Marshaljson () ([]byte, error)//marshal JSON serialization, serialized by T, and deposited into []byte array]


Func (t time) Marshaltext () ([]byte, error)//marshal text serialization, serializing time t into []byte array]

Example: A: = time. Now () Fmt. PRINTLN (a) output: 2014-11-27 14:58:31.583853811 +0800 CST B, _: = A.marshaltext () fmt.     PRINTLN (b) Output: [50 48 49 52 45 49 49 45 50 55 84 49 52 58 53 56 58 51 49 46 53 56 51 56 53 51 56 49 49 43 48 56 58 48 48] var C = new (time. Time) Fmt. PRINTLN (c) Output: 0001-01-01 00:00:00 +0000 UTC c.unmarshaltext (b) fmt. PRINTLN (c) Output: 2014-11-27 14:58:31.583853811 +0800 CST Visible the function of the Marshal class is simply to provide a function that serializes the time t into the []byte array], The function of the Unmarshal class can be used to obtain the original time t

Func (t time) Minute () int//Gets the minute of the time t


Func (t time) month () month//Get time t


Func (t time) nanosecond () int//Get nanosecond of time t


Func (t time) Round (d Duration) time//The approximate value is rounded in D Duration.

Examples are as follows:

Code:

T: = time. Date (0, 0, 0, 918273645, time). UTC) Round: = []time. duration{time    . nanosecond, Time    . Microsecond,    Time.millisecond, Time    . Second,    2 * time. Second, Time    . Minute,    Ten * time. Minute, Time    . Hour,}for _, D: = Range round {    FMT. Printf ("T.round (%6s) =%s\n", D, T.round (d). Format ("15:04:05.999999999"))}

Output:

T.round (   1ns) = 12:15:30.918273645t. Round (   1µs) = 12:15:30.918274t. Round (   1ms) = 12:15:30.918t. Round (    1s) = 12:15:31t. Round (    2s) = 12:15:30t. Round (  1m0s) = 12:16:00t. Round (10m0s) = 12:20:00t. Round (1h0m0s) = 12:00:00

Func (t time) Second () int//Gets the seconds of the time t


Func (t time) string () string representation of the time t () string//Get


Func (t time) sub (U time) Duration//In contrast to add, Sub means subtracting time from time t u


Func (t time) Truncate (d Duration) time//de-tailed method for approximate values

The sample code is as follows:

Code:

T, _: = time. Parse ("2006 Jan 15:04:05", "Dec 12:15:30.918273645") trunc: = []time. duration{time    . nanosecond, Time    . Microsecond,    Time.millisecond, Time    . Second,    2 * time. Second, Time    . Minute,    Ten * time. Minute, Time    . Hour,}for _, D: = Range trunc {    fmt. Printf ("t.truncate (%6s) =%s\n", D, T.truncate (d). Format ("15:04:05.999999999"))}

Output:

T.truncate (   1ns) = 12:15:30.918273645t. Truncate (   1µs) = 12:15:30.918273t. Truncate (   1ms) = 12:15:30.918t. Truncate (    1s) = 12:15:30t. Truncate (    2s) = 12:15:30t. Truncate (  1m0s) = 12:15:00t. Truncate (10m0s) = 12:10:00t. Truncate (1h0m0s) = 12:00:00


Func (T-time) UTC () time//convert local times to UTC timezone and return


Func (T-time) UNIX () Int64//returns UNIX, which is calculated starting from January 1, 1970 UTC at this time.


Func (t time) Unixnano () Int64//return UNIX times in nanoseconds


Func (t *time) unmarshalbinary (data []byte) error//deserializing data data into time t


Func (t *time) unmarshaljson (data []byte) (Err Error)//deserializing data data into time t


Func (t *time) unmarshaltext (data []byte) (Err Error)//deserializing data data into time t


Func (t time) Weekday () Weekday//Get Weekday of time t


Func (T time) year () int//Get time t


Func (t time) yearday () int//Gets the yearday of the time t, that is, the day of the Year 1


Func (t time) Zone () (name string, offset int)


The type timer//is used to call a function or evaluation expression after the specified duration type time, which is a timer


Func Afterfunc (d Duration, F func ()) *timer//And after approximately, meaning how long after the function f is executed


Func Newtimer (d Duration) *timer//Using Newtimer (), can return a timer type before the timer expires, cancels the timer


Func (t *timer) Reset (d Duration) bool//reset Timer t Duration d.


Func (t *timer) stop () bool//Block Timer event occurs when the timer timer stops after the function executes and the corresponding event is no longer executed


One) type Weekday
Func (d Weekday) string () string//Get a week's string






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.