4

I'm trying to understand what the difference is between time.Now() and time.Now().Local(). I started by printing them out on my laptop (running Ubuntu 18.04):

fmt.Println(time.Now())
fmt.Println(time.Now().Local())

which gives me

2018-12-23 19:57:08.606595466 +0100 CET m=+0.000583834
2018-12-23 19:57:08.606667843 +0100 CET

I'm not sure what the m=+0.000583834 is. Maybe the difference between my machine and the NTP servers?

I then checked out the docs on .Now() and .Local(), which read:

Now returns the current local time.

and

Local returns t with the location set to local time.

Both of them return local time, so I'm still unsure what the difference is. I tried searching around, but I couldn't really find definite answers.

Could anyone shed some light on this?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

7

time.Now().Local() sets the time's Location to local time. time.Now() is already set to local time, so there's no net effect except that m bit.

The m portion is the Monotonic Clock.

Operating systems provide both a “wall clock,” which is subject to changes for clock synchronization, and a “monotonic clock,” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time.

A monotonic clock is basically a simple count since the program started. m=+0.000583834 says that time is 0.000583834 seconds after the program started.

time.Now().Local() explicitly strips the monotonic clock...

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

Schwern
  • 153,029
  • 25
  • 195
  • 336
  • 1
    Wow, I never realised the difference between the wall clock and the monotonic clock. And for the program which I'm writing (a self learning auto pilot for an rc-plane) measuring time is way more important than telling time. One more question: does `time.Since()` use the monotonic clock or the wall clock? And if `time.Since()` uses the wall clock, how can tell the difference in monotonic time between two time objects? – kramer65 Dec 23 '18 at 20:27
  • 1
    @kramer65 As the docs say, "*Other idioms, such as time.Since(start), time.Until(deadline), and time.Now().Before(deadline), are similarly robust against wall clock resets.*" and Since() "*is shorthand for time.Now().Sub(t)*". You can subtract two Times and get a `Duration` which is just a count of nanoseconds. – Schwern Dec 23 '18 at 20:47