Golang Time Programming

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

Programming is inseparable from time, time management, strictly speaking divided into two pieces, one is the current moment, corresponding to a point, there is a period of time interval. This article simply talk about the time-related programming of go, relatively simple, the master can smile.

Golang time Support, is the package to do things, there are a lot of functions, I do not give an example of learning, after all, this is the official document to do. Our initial study of the commonly used functions.

The first is the Unix epoch time, which is exactly the number of seconds since 1970-01-01 00:00:00 GMT, and does not know how to get it, and can execute the date +%s under the shell.

One of the most important representations in Golang is time, which is basically three member variables sec, nsec,location, and the detailed meaning can be noted in the comments.

Type time struct {           // sec  gives the number of seconds elapsed since             // january 1, year 1 00:00:00 utc.             sec int64                     // nsec  specifies a non-negative nanosecond             // offset within the second named by Seconds.             // it must be in the  range [0, 999999999].             Nsec int32                      loc specifies the Location that should be used to             // determine the minute, hour,  month, day, and year             // that correspond to this Time.             // only the zero time has a nil location .            // in that case  it is interpreted to mean utc.             loc *location        }

OK, how to access the Unix epoch time.

Now: = time. Now ()

The now () function is very important to get the current time information by using the Today () function in the Times package, which is the starting point for all subsequent conversions. From now () we get to time, from the type we take calmly to the Unix epoch time, which naturally gets to year, month, Day,weekday, Hour,minute,second,nanosecond.

Get the Unix epoch time:

var epoch_seconds int64 = Now. Unix ()

Get Year

Func (T time) year () Intcur_year: = Now. Year ()

Get Month

Func (t time) Month () Monthcur_month: = Now. Month () if cur_month = = time. November {...}

Month is the int type, FMT. Printf ("%v") or FMT. Println can print out the November, and the month type has a string () function, which outputs "November" such as strings

Const (January Month = 1 + Iota February March April may June July August September October November December)

Year Mon day, which can all be returned in the DATE function:

Func (t time) Date () (year int, month month, day int) Year,mon,day = now. Date ()

Get Hour

Func (t time) Hour () int Cur_hour: = now. Hour ()

Minute can be returned by minute (), second can be returned by second ().

Time also provides the simultaneous return of clock () Hour,minute,second = Now. Clock ().

Package Mainimport "FMT" import "Time" Func main () {now: = time. Now () Year,mon,day: = Now. UTC (). Date () Hour,min,sec: = Now. UTC (). Clock () Zone,_: = Now. UTC (). Zone () fmt. Printf ("UTC time is%d-%d-%d%02d:%02d:%02d%s\n", year,mon,day,hour,min,sec,zone) Year,mon,day = Now. Date () Hour,min,sec = Now. Clock () Zone,_ = Now. Zone () fmt. Printf ("local time is%d-%d-%d%02d:%02d:%02d%s\n", Year,mon,day,hour,min,sec,zone)}

Go version output---------------------UTC time is 2013-11-22 15:51:22 utclocal time is 2013-11-22 23:51:22 CST

Another topic of concern to us is the time interval, for example, we profile a very time-consuming function, we will write down the time value before the function starts, after the function is finished, record the time value again, and then the difference between the two is the function run time.

This shows that time can be subtracted.

Start_time: = time. Now () Expensive_functionend_time: =time. Now () var duration duration = End_time. Sub (start_time)

Duration is a data type that is actually a int64 type, characterizing the number of nanoseconds between two moments.

Type Duration int64const (nanosecond Duration = 1 microsecond = $ * nanosecond millisecond = 1000 * Microsecond Second = $ * Millisecond Minute = $ * Second Hour = $ * Minute)

The duration type has minutes ()/second ()/nanoseconds (), which translates duration into minutes per second/nanosecond.

Now: = time. Now () time. Sleep (3*time.    Second); End_time: = time. Now () var dur_time time. Duration = End_time. Sub (now) var elapsed_min float64 = Dur_time. Minutes () var elapsed_sec float64 = Dur_time. Seconds () var Elapsed_nano int64 = Dur_time. nanoseconds () fmt. Printf ("elasped%f minutes or \nelapsed%f seconds or \nelapsed%d nanoseconds\n", Elapsed_min,elapsed_sec, Elapsed_nano)

The output is as follows

elasped 0.050005 minutes or elapsed 3.000292 seconds or elapsed 3000292435 nanoseconds

The time.sleep in Go are in nanoseconds, of course the duration type:

Sleep 3 seconds can be written

Time. Sleep (3000000000)

Time. Sleep (3*time. Second);


package main import  (     "FMT"      "Time")  const   (    date        =  "2006-01-02"      shortdate   =  "06-01-02"     times        =  "15:04:02"     shorttime   =  "15:04"     datetime    =  "2006-01-02 15:04:02"      newdatetime =  "2006/01/02 15~04~02"     newtime      =  "15~04~02")  func main ()  {    thisdate :=  " 2014-03-17 14:55:06 "    timeformatdate, _ := time. Parse (datetime, thisdate)     fmt. Println (timeformatdate)     convdate := timeformatdate. Format (date)  &NBsp;  convshortdate := timeformatdate. Format (shortdate)     convtime := timeformatdate. Format (Times)     convshorttime := timeformatdate. Format (Shorttime)     convnewdatetime := timeformatdate. Format (Newdatetime)     convnewtime := timeformatdate. Format (NewTime)     fmt. Println (convdate)     fmt. Println (convshortdate)     fmt. Println (Convtime)     fmt. Println (Convshorttime)     fmt. Println (Convnewdatetime)     fmt. Println (Convnewtime)}


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.