Explain the time in the Go language. Duration type

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. For a long time, I have been mad at the time package in the Go standard library, my mania comes from two functions, one is the number of milliseconds to capture the interval between two different time periods, and the second is to compare a sequential period of milliseconds with a predefined time period. It sounds simple, yes, it does, but it really makes me mad. In the time package, you define a type named Duration and some auxiliary constants: "' Gotype Duration int64const (nanosecond Duration = 1Microsecond = + * Nanoseco Ndmillisecond = $ * Microsecondsecond = + * Millisecondminute = * Secondhour = * Minute) ' ' These things I may have seen thousands of, but My brain is still confused. I just want to compare two time periods, restore the time to last, compare the duration of the time and do something else when the preset time runs out, but the structure still doesn't solve my problem anyway. I wrote down the following test code, but it has no ova: "' Gofunc Test () {var waitfivehundredmillisections int64 = 500startingTime: = time. Now (). UTC () time. Sleep (Ten * time.millisecond) Endingtime: = time. Now (). UTC () var duration time. Duration = Endingtime.sub (startingtime) var durationAsInt64 = Int64 (Duration) if DurationAsInt64 >= waitfivehundredmillisections {fmt. Printf ("Time elapsed:wait[%d] duration[%d]\n", Waitfivehundredmillisections, DurationAsInt64)} else {fmt. Printf ("Time did not elapsed:wait[%d] duration[%d]\n", Waitfivehundredmillisections, DurationasinT64}} "I ran this test code and got the following output, from the output, I defined 500 milliseconds elapsed, but how possible. "Time elapsed:wait[500] duration[10724798]" "So where's the problem? Once again I've turned my eyes to the definition of the Duration type: "Gotype Duration int64const (nanosecond Duration = 1Microsecond = + * Nanosecondmillisecond = * Microsecondsecond = + * Millisecondminute = * Secondhour = * Minute) ' ' From the Code, the basic unit of time in Duration type is Nan Osecond, so when I convert a Duration type object representing 10 milliseconds to a int64 type, I actually get 10,000,000. So the direct conversion is not possible, I need a different strategy to use and convert the Duration type. I know it's best to use the data defined in the Duration type, which will minimize the problem. Based on the constants defined in Duration, I can create a Duration variable like this: ' Gofunc Test () {var duration_milliseconds time. Duration = * Time.millisecondvar duration_seconds time. Duration = (1250 *) * Time.millisecondvar duration_minute time. Duration = 2 * time. minutefmt.printf ("Milli [%v]\nseconds [%v]\nminute] [%v]\n", Duration_milliseconds, Duration_seconds, Duration_Minute } "in the code above, I created 3 variables of type Duration, and by using the time constant, I was able to create the correct duration value. Then I used the standard library function ' Printf ' and the '%v ' operator to get the following output: ' ' Milli [500ms]seconDS [12.5s]minute [2m0s] "cool, have wood?" The ' Printf ' function knows how to localize the display of a Duration type, which is based on each value in the Duration type, selects the appropriate format for the time display, and of course I get the expected results. In fact, the Duration type has some handy type conversion functions that can convert the Duration type to the built-in type Int64 or float64 of the Go language, like this: "' Gofunc Test () {var duration_seconds Time. Duration = (1250 *) * time. Millisecondvar duration_minute time. Duration = 2 * time. Minutevar float64_seconds float64 = Duration_seconds.seconds () var float64_minutes float64 = Duration_minute.minutes () Fmt. Printf ("Seconds [%.3f]\nminutes [%.2f]\n", Float64_seconds, Float64_minutes)} ' I also quickly noticed that in the time conversion function, there is no function to convert the millisecond value, using the Seconds and Minutes functions, I got the following output: ' ' Seconds [12.500]minutes [2.00] ' But I need to convert the millisecond value, why does the packet not provide a conversion of milliseconds? Because the designers of the Go language wanted me to have more options than just converting the millisecond value into a single built-in type. In the following code, I convert the millisecond value to the Int64 type and float64 type: ' Gofunc Test () {var duration_milliseconds time. Duration = * time. Millisecondvar CastToInt64 Int64 = Duration_milliseconds.nanoseconds ()/1e6var castToFloat64 float64 = Duration_ Milliseconds.seconds () * 1e3fmt. Printf ("Duration [%v]\ncasttoint64 [%D]\ncasttofloat64 [%.0f]\n ", Duration_milliseconds, CastToInt64, CastToFloat64)}" I divide the nanosecond value by 1^6 to get the millisecond value represented by the int64 type, Multiplying the seconds value by 1^3, I get the millisecond value represented by the Float64 type, and the output of the above code is as follows: "' Duration [500ms]casttoint64 [500]casttofloat64 [500]" Now, I know Duration What the type is and how to use it, here is an example of a test code that I finally wrote with a millisecond value: "' Gofunc Test () {var waitfivehundredmillisections time. Duration = * Time.millisecondstartingtime: = time. Now (). UTC () time. Sleep (* time.millisecond) Endingtime: = time. Now (). UTC () var duration time. Duration = Endingtime.sub (startingtime) if Duration >= waitfivehundredmillisections {fmt. Printf ("Wait%v\nnative" [%v]\nmilliseconds [%d]\nseconds [%.3f]\n], Waitfivehundredmillisections, duration, duration. nanoseconds ()/1e6, duration. The output of Seconds ()}} "is as follows:" ' Wait 500msNative [601.091066ms]milliseconds [601]seconds [0.601] ' does not determine whether the time is exhausted by comparing the local type , instead of comparing two Duration type variables, this is clearer. Although it took some time, I finally understood the Duration type, and I hope this article will help others to solve the Duration type of confusion in the process of using the Go language.

Via:https://www.ardanlabs.com/blog/2013/06/gos-duration-type-unravelled.html

Author: William Kennedy Translator: Swardsman proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

3,693 Reads

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.