Unexpected output from time.Time

后端 未结 3 904
栀梦
栀梦 2020-12-10 20:35

I just started to learn Go by following a tutorial video on Udemy, and I tried to print the current time as below

import (
  \"fmt\" 
  \"time\"
)

func main         


        
3条回答
  •  半阙折子戏
    2020-12-10 21:04

    Your Udemy tutorial video is out-of-date. Go is continually updated. For example, a monotonic clock bug fix:

    Go 1.9 Release Notes (August 2017)

    Transparent Monotonic Time support

    The time package now transparently tracks monotonic time in each Time value, making computing durations between two Time values a safe operation in the presence of wall clock adjustments. See the package docs and design document for details.

    As always, there are various minor changes and updates to the library, made with the Go 1 promise of compatibility in mind.

    time

    If a Time value has a monotonic clock reading, its string representation (as returned by String) now includes a final field "m=±value", where value is the monotonic clock reading formatted as a decimal number of seconds.


    Package time

    import "time"

    The Time returned by time.Now contains a monotonic clock reading. If Time t has a monotonic clock reading, t.Add adds the same duration to both the wall clock and monotonic clock readings to compute the result. Because t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time computations, they always strip any monotonic clock reading from their results. Because t.In, t.Local, and t.UTC are used for their effect on the interpretation of the wall time, they also strip any monotonic clock reading from their results. The canonical way to strip a monotonic clock reading is to use t = t.Round(0).


    fmt.Println(t) uses a debugging format so it prints all the underlying time.Time fields.

    The canonical way to strip a monotonic clock reading is to use t = t.Round(0).

    For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        t := time.Now()
        fmt.Println(t)
        fmt.Println(t.Round(0))
    
        t2 := time.Now().Round(0)
        fmt.Println(t2)
    }
    

    Playground: https://play.golang.org/p/p_pjRWRB8_y

    Output:

    2009-11-10 23:00:00 +0000 UTC m=+0.000000001
    2009-11-10 23:00:00 +0000 UTC
    2009-11-10 23:00:00 +0000 UTC
    

提交回复
热议问题