Golang time and date related functions

1, Basic introduction

In programming, programmers often use date related functions, such as counting the time spent on the execution of a piece of code and so on. In Go, the developer provides us with a time package for displaying time and measuring usage (the Gregorian calendar is used for calendar calculation). For details, see: Golang's standard library

1) time.Time type: used to represent time

package main
import (
    "fmt"
    "time"
)
func main() {
	// View current time
    now := time.Now()
    // When used directly, the output is the current time, time zone and milliseconds
    fmt.Printf("now type = %T && now = %v",now,now)
}

Output: now type = time. Time & & now = 2021-12-04 14:26:56.096042 + 0800 CST M = + 0.002252801

2) View the display information of each time

package main
import (
    "fmt"
    "time"
)
func main() {
    now := time.Now()
    fmt.Printf("year = %v\n",now.Year())
    // Because the month output is in English, we can use int to escape
    fmt.Printf("month = %v\n",int(now.Month()))
    fmt.Printf("day = %v\n",now.Day())
    fmt.Printf("Time = %v\n",now.Hour())
    fmt.Printf("branch = %v\n",now.Minute())
    fmt.Printf("second = %v\n",now.Second())
}

1. Format date and time

1) Both Printf and Sprintf are available

package main
import (
	"fmt"
	"time"
)
func main() {
	now := time.Now()
	fmt.Printf("Current date: %d-%d-%d %d:%d:%d\n",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())

	dateStr := fmt.Sprintf("Current date: %d-%d-%d %d:%d:%d\n",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())
	fmt.Printf("dateStr = %v",dateStr)
}

2) By time.Format()

package main
import (
    "fmt"
    "time"
)
func main() {
    now := time.Now()
    // View current year, month and time
    fmt.Printf(now.Format("2006-01-02 15:04:05"))
    fmt.Println()
    // View the current month of the previous year
    fmt.Printf(now.Format("2006-01-02"))
    fmt.Println()
    // View current time
    fmt.Println(now.Format("15:04:05"))
    fmt.Println()
}
  • PS: 2006 / 01 / 02 15:04:05 this format is fixed and cannot be customized according to the current time.

2. Time constant

conse (
    Nanosecond   =  1ns (nanosecond)  
    Microsecond  =  1000 * Nanosecond   =  1 (Microsecond)
    Millisecond  =  1000 * Microsecond  =  1 (millisecond)
    Second		 =  1000 * Millisecond  =  1 (second)
    Minute		 =  60   * Second       =  1 (minute)
    Hour 		 =  60   * Minute	    =  1 (hour)
)
  • Function of constant: it can be used to obtain the time in the specified time unit in the program. For example, we want to get 100 milliseconds (100 * time.Millisecond)

1) The time constant is used in conjunction with Sleep

package main
import (
    "fmt"
    "time"
)
func main() {
    // Print a number every 0.1 seconds. Exit when printing to 100
    i := 0
    for {
        i++ 
        fmt.Println(i)
        time.Sleep(time.Millisecond * 100)
        // When the conditions are met, the loop exits
        if i == 100 {
            break
        }
    }
}
        

2) Use of Unix and UnixNano in time:

package main
import (
	"fmt"
	"time"
)
func main() {
	now := time.Now()
	fmt.Printf("Unix Timestamp of = %v && Unixnano Timestamp of = %v",now.Unix(),now.UnixNano())
}
  • Output: Unix timestamp = 1638604549 & & UNIX nano timestamp = 1638604549410002500

The difference between Unix and Unix NAO is that the former displays seconds, while the latter displays nanoseconds (both of which have been since January 1, 1970)

2, Introduction to use

Count the execution time of test() function:

package main
import (
    "fmt"
    "time"
    "strconv"
)
func test() {
    str := ""
    for i := 0; i < 100000; i++ {
    	// The function of strconv.Itoa is to convert integers into strings
        str += "Hello" + strconv.Itoa(i)
    }
}
func main() {
    // Get the current Unix timestamp before executing test()
    start := time.Now().Unix()
    test()
    end := time.Now().Unix()
    fmt.Printf("implement test() Time consuming %v second",end - start) // Subtract the time before execution from the time after completion
}

1. Built in function

In Go, developers provide some functions for programming convenience. These functions can be used directly. We call them Go's built-in functions.

  1. len: used to count string length, such as string array slice map channel.
  2. new: used to allocate memory. It is mainly used to allocate value types, such as int float32 struct, and returns pointers.
  3. make: used to allocate memory addresses. It is mainly used to allocate reference types, such as channel map slice, etc.

The above is only part of the built-in functions. For more built-in functions, see: Golang standard library (in builtin package)

Introduction to new:

package main
import (
	"fmt"
)
func main() {
	num := 100
	fmt.Printf("num Type of = %T && num Value of = %v && num Memory address of = %v\n",num,num,&num)
	ptr := new(int) // *int (pointer type)
	*ptr = 100
	fmt.Printf("ptr Type of = %T && ptr Value of = %v && ptr Memory address of = %v && ptr The value pointed to by this pointer is = %v",ptr,ptr,&ptr,*ptr)
}
  • new actually allocates a space, installs a value (0), and then allocates a space to store the memory address of this value;
  • Finally, point the defined variable value to the memory address of the stored value.

Output:

num Type of = int && num Value of = 100 && num Memory address of = 0xc00000a098
ptr Type of = *int && ptr Value of = 0xc00000a0d0 && ptr Memory address of = 0xc000006030 && ptr The value pointed to by this pointer is = 100

Tags: Go function

Posted on Sun, 05 Dec 2021 00:45:53 -0500 by purencool