Reader small image

You're reading from  Go Programming - From Beginner to Professional - Second Edition

Product typeBook
Published inMar 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781803243054
Edition2nd Edition
Languages
Right arrow
Author (1)
Samantha Coyle
Samantha Coyle
author image
Samantha Coyle

Samantha Coyle, a Software Engineer at Diagrid, specializes in Go for cloud-native developer tooling, abstracting application development challenges. Committed to Open Source, she contributes to projects like Dapr and Testcontainers. She boasts a rich history in retail computer vision solutions and successfully stabilized industrial edge use cases with testing and diverse deployments for biopharma data pipelines. Her expertise extends to being CKAD certified and reviewing Go textbooks. She is passionate about empowering early-career, diverse professionals. Samantha is in a family of gophers, and enjoys GopherCon with her brother and identical twin sister. She's a seasoned speaker, having presented at various conferences, including GopherCon.
Read more about Samantha Coyle

Right arrow

About Time

Overview

This chapter demonstrates how Go handles variables representing time data, which is a very important aspect of the language.

By the end of this chapter, you will be able to create your own time format, compare and manage time, calculate the duration of time series, and format time according to user requirements.

Technical requirements

For this chapter, you'll require Go version 1.21 or higher. The code for this chapter can be found at: https://github.com/PacktPublishing/Go-Programming-From-Beginner-to-Professional-Second-Edition-/blob/main/Chapter12.

Introduction

The previous chapter introduced you to basic debugging in Go. The more you develop code in Go, the better you get; however, developing and deploying code may come with corner cases that need to be debugged. The previous chapter showed you how to use the fmt package, how to log in to files, and how to use printing verbs for string formatting.

This chapter is dedicated to teaching you all you need to know about handling variables that represent time data. You will learn how to do it the “Go way.” First, we will start out with basic time creation, timestamps, and more; then, we will learn how to compare and manipulate time, calculate the duration between two dates, and create timestamps. Finally, we will learn how to format time according to our needs. So, let’s not waste any more time and jump right in.

Making time

Making time means declaring a variable that holds the time formatted in a specific way. Formatting time will be covered at the end of this chapter; so, for now, we will use the default formatting that is provided by Go. In this topic, we will be executing everything in the main() function of our script, so the skeleton should look like this:

package main
import (
  "fmt"
  "time"
)
func main(){
  // this is where the code goes.
}

Let’s look at our skeleton first and learn how to create and manipulate time variables. Our skeleton has the standard package main definition that is necessary. We use the fmt package to print the output to the console. Since we’ll be using the time package, we’ll need to import that as well.

Whenever we issue go run <script>.go, the main() function gets called and executes whatever is declared in it.

One of the most common jobs for the time package is to measure...

Comparing time

Most of the time, when working with Go on smaller scripts, it is very important for your statistics to know when a script should run, or between what hours and minutes a script should be completed. By statistics, we mean knowing how much time the app saves by executing a specific operation compared to what time cost it would have if we had to perform these manually. This allows us to measure the improvement of the script over time when we develop the functionality further. In this topic, we will look at some live examples demonstrating how you can solve this problem.

Let’s look at the logic for the first script, which was intended not to run before or after a specified time. This time can arrive either via another automation or when a trigger file is manually placed there; every day, the script needs to run at different times –specifically, after the specified time as soon as possible.

The time was in the following 2023-09-27T22:08:41+00:00 format...

Duration calculation

The ability to calculate the duration of an execution comes in handy during many aspects of programming. In our everyday lives, we can monitor discrepancies and performance bottlenecks that our infrastructure might face. For example, if you have a script that takes only 5 seconds to complete on average and the monitoring execution time shows you a huge bump during certain hours of a day or certain days, it might be wise to investigate. The other aspect is related to web applications. Measuring the duration of request-response in your scripts can give you an insight into how well invested you are in your apps to serve high loads, and it even allows you to expand your capacity on certain days or weeks of the year. For example, if you have an online shop dealing with products, it might be wise to size your capacity according to patterns such as Black Friday or Christmas.

You may do well with a lower capacity during most of the year, but those holidays can result...

Managing time

The Go programming language’s time package provides two functions that allow you to manipulate time. One of them is called Sub(), and the other one is called Add(). There have not been many cases, in my experience, where this has been used. Mostly, when calculating the elapsed time of a script’s execution, the Sub() function is used to tell the difference.

Let’s see what the addition looks like:

  timeToManipulate := time.Now()
  toBeAdded := time.Duration(10 * time.Second)
  fmt.Println("The original time:", timeToManipulate)
  fmt.Printf("%v duration later %v", toBeAdded, timeToManipulate.Add(toBeAdded))

After execution, the following output welcomes us:

The original time: 2023-10-18 08:49:53.1499273 +0200 CEST m=+0.001994601
10s duration later: 2023-10-18 08:50:03.1499273 +0200 CEST m=+10.001994601

Let’s inspect what happened here. We created a variable to hold our...

Formatting time

So far in this chapter, you may have noticed that the dates are pretty ugly. I mean, take a look at the following lines:

The transaction has started at: 2023-09-27 13:50:58.2715452 +0200 CEST m=+0.002992801

These were intentionally left there to force you to think about whether this is all that Go can do. Is there a way to format these lines to make them more convenient and easier to read? If so, what are those extra lines?

Here, we will answer those questions. When we talk about time formatting, there are two main concepts we are referring to. The first option is for instances when we would like our time variable to output a desirable-looking string when we use it in print, and the second option is for when we would like to take a string and parse it to a specific format. Both have their own use cases; we are going to look at them in more detail as I teach you how to use both.

First, we are going to learn about the Parse() function. This function has essentially...

Summary

This chapter introduced you to the time package of Go, which allows you to reuse code that has been invented by other programmers and incorporated into the language. The goal was to teach you how to create, manipulate, and format time variables, and, in general, make you familiar with what you can do with the help of the time package. If you would like to further improve or dig deeper into what the package has to offer, you should check out the following link: https://golang.org/pkg/time/.

Timestamps and time manipulation are essential skills for every developer. Whether you have a big or small script put into production, the time module helps you to measure the elapsed time of actions and provide you with the logging of actions that happen during the execution. The most important thing about it, if used correctly, is that it helps you to easily trace back production problems to their roots.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Go Programming - From Beginner to Professional - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781803243054
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Samantha Coyle

Samantha Coyle, a Software Engineer at Diagrid, specializes in Go for cloud-native developer tooling, abstracting application development challenges. Committed to Open Source, she contributes to projects like Dapr and Testcontainers. She boasts a rich history in retail computer vision solutions and successfully stabilized industrial edge use cases with testing and diverse deployments for biopharma data pipelines. Her expertise extends to being CKAD certified and reviewing Go textbooks. She is passionate about empowering early-career, diverse professionals. Samantha is in a family of gophers, and enjoys GopherCon with her brother and identical twin sister. She's a seasoned speaker, having presented at various conferences, including GopherCon.
Read more about Samantha Coyle