Remove Monotonic Clock Reading from time.Time

Avatar of the author Willem Schots
22 Jan, 2024
~1 min.
RSS

Maybe you have noticed the m+=0.000123 part at the end of a string when printing a time.Time value created via time.Now().

This is a monotonic clock reading. If you want to learn more, check my article on time.Now() and the Monotonic Clock it’s all about this subject.

You might want to remove this monotonic clock reading to:

  • Remove it from the String() output for consistency and compatibility reasons.
  • Use time.Time values as map keys.

The preferred way to only strip the monotonic clock reading is by calling time.Round(0). This will create a new time.Time value with only a wall clock reading (and a location reference). See the example below.

There are other functions that remove the monotonic clock element as a side effect. For example: t.UTC(), t.Local() and the decoding/encoding functions.

main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	// t1 has a monotonic element
	t1 := time.Now()
	// t2 does not
	t2 := t1.Round(0)

	fmt.Println(t1.String())
	fmt.Println(t2.String())
}

Career choice: Learn skills to mitigate the upcoming AI privacy disaster*

Join 800+ devs reading my newsletter

*Everyone and their mother is sending sensitive data to AI systems with little concern for their privacy. If you read the fineprint, vendors and platforms actually offer very little guarantees. It's a matter of time before it goes wrong.

From March 2026 onwards, I'll be writing about development of verifiably-secure services using OpenPCC.

Avatar of the author
Willem Schots

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Bluesky, Twitter/X or LinkedIn.

Thanks for reading!