SoFunction
Updated on 2025-03-05

Detailed explanation of the use of time functions for Go language learning

introduction

On February 14, 1946, the first modern electronic computer recognized in human history, "ENIAC", was born.

The computer language timestamp is based on 0:00 on January 1, 1970 as the starting point. The computer was born on February 14, 1946, and the time to give vitality began at 0:00 on January 1, 1970.

Hour 1 hour = 60 minutes

Minute 1 minute = 60 seconds

Second 1 second = 1000 milliseconds

Millsecond 1 millisecond = 1000 microseconds

Microsecond 1 microsecond = 1000 nanoseconds

Nanoseco 1 nanosecond

1. Time formatting

2006/1/02 15:04:05 This time must be fixed and cannot be changed, otherwise the correct time cannot be obtained

package main

import (
	"fmt"
	"time"
)

func main() {
	//Format string	now := ()
	//The time must be fixed and cannot be changed, otherwise the correct time cannot be obtained	(("02/1/2006 15:04:05"))
	(("2006/1/02 15:04"))
	(("2006/1/02"))
}

The output result is as follows

07/4/2022 21:51:52
2022/4/07 21:51
2022/4/07

2. Example

Extract the date of the acquisition and determine whether it is a member day

package main

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

func main() {
	//Format string	now := ()
	//The time must be fixed	times := ("2006/1/02 15:04:05")

	a := (times)
	(a[0])
	(a[1])
	b := (a[0], "/")
	(b[2])
	
	//Judge whether it is a member day, odd number is a member day, and even number is a non-member day	c, _ := (b[2])
	if c%2 != 0 {
		("Membership Day")
	} else {
		("Non-member day")
	}
}

The output result is as follows

2022/4/07
22:07:42
07
Membership Day

Statistics program execution time, accurate to microseconds

package main

import (
	"fmt"
	"time"
)

func main() {
	// Use timestamp to count the time	start := ().UnixNano()
	sleepTime()
	end := ().UnixNano()
	("Program execution time: %d", (end-start)/1000)
}

func sleepTime() {
	( * 100)
}

The execution results are as follows

Program execution time: 113650

This is the end of this article about the detailed explanation of the use of time functions for Go language learning. For more relevant content on Go language time functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!