Chapter 11. Date and Time Recipes
11.0 Introduction
Time (and as an extension of that, date) manipulation is an important part of any programming language. We use it to keep track of time, calculate the elapsed duration between times, format dates and times for representation, and much more. However, time manipulation is often not as straightforward as it seems.
Our computers have two different types of clocks—a wall clock and a monotonic clock. The wall clock is what we’re used to and is literally a wall clock that we look at to determine the time of day. The wall clock is usually synchronized with a Network Time Protocol (NTP) server to set the correct time on the computer. As a result, the wall clock can sometimes jump back and forth.
Also, the clock itself might be adjusted by a user or another program, so if you’re using the wall clock to measure duration, the timing might not be accurate. For example, if the clock is changed while you’re trying to measure how long a task takes, the results might become a negative number!
A monotonic clock, on the other hand, provides a time that is always going forward. With the same example, you won’t be affected by clock changes or adjustments. In general, you should be using the wall clock to tell the time, and the monotonic clock to measure duration.
Like many programming languages, Go has a pretty good package to help with time and it’s called (no surprise here) the time package.
11.1 Telling Time
Problem
You want to know the current ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access