Go ----- common functions (strings, time)

Keywords: Go

Go common functions

Official website: https://golang.org/pkg/ golang official website

1, strings handles string related

Statistics string length, in bytes                   len(str)

String traversal,Processing Chinese                    r:=[]rune(str)

String to integer                           n, err := strconv.Atoi("12")

Integer to string                           str = strconv.Itoa(12345)

String conversion []byte                   var bytes = []byte("hello go")

[]byte To string                   str = string([]byte{97, 98, 99})

10 Binary to 2, 8, 16 Base system:              str = strconv.FormatInt(123, 2) // 2-> 8 , 16

Finds whether the substring is in the specified string             strings.Contains("seafood", "foo") //true

Counts how many specified substrings a string has         strings.Count("ceheese", "e") //4

Case insensitive string comparison(==It is case sensitive)  fmt.Println(strings.EqualFold("abc", "Abc")) // true

Returns the first occurrence of a substring in a string index Value, if not returned-1      strings.Index("NLT_abc", "abc") // 4

Returns the last occurrence of a substring in a string index,If no return-1         strings.LastIndex("go golang", "go")

Replaces the specified substring with another substring strings.Replace("go go hello", "go", "go language", n) ,n You can specify how many you want to replace if n=-1 Means replace all

Splits a string into a string array according to a specified character for the split identifier  strings.Split("hello,wrold,ok", ",")

Converts the letters of a string to case: strings.ToLower("Go") // go strings.ToUpper("Go") // GO

Remove the spaces on the left and right sides of the string: strings.TrimSpace(" tn a lone gopher ntrn ")

Remove the characters specified on the left and right sides of the string : strings.Trim("! hello! ", " !") 

Removes the specified character from the left of the string : strings.TrimLeft("! hello! ", " !")

Removes the specified character from the right side of the string :strings.TrimRight("! hello! ", " !")

Determines whether the string starts with the specified string: strings.HasPrefix("ftp://192.168.10.1", "ftp") 

Determines whether the string ends with the specified string: strings.HasSuffix("NLT_abc.jpg", "abc") //false

2, Time date function

1. Basic package

package time
//The time package provides functions for time display and measurement. Calendar calculation uses the Gregorian calendar
package main
import (
    "fmt"
    "time"
)
func main() {
    //Get current time
    now := time.Now()
    fmt.Printf("Current time:%v\n", now)
    fmt.Printf("Current time type%T\n", now)
    //Obtain the hour, minute and second of month, day and year through now
    fmt.Printf("The current time is years=%v month=%v day=%v Time=%v branch=%v second=%v\n", now.Year(), int(now.Month()), now.Day(), now.Hour(), now.Minute(), now.Second())
    //The time is formatted. The time is fixed at 15:04:05, January 2, 2006. It must be written like this
    fmt.Printf(now.Format("2006-01-02 15:04:05\n"))
}

2. Timestamp

The timestamp is the total number of milliseconds from January 1, 1970 (08:00:00GMT) to the current time. It is also called Unix timestamp

func timestampDemo() {
	now := time.Now()            //Get current time
	timestamp1 := now.Unix()     //time stamp
	timestamp2 := now.UnixNano() //Nanosecond timestamp
	fmt.Printf("current timestamp1:%v\n", timestamp1)
	fmt.Printf("current timestamp2:%v\n", timestamp2)
}

The timestamp can be converted to time format using the time.Unix() function.

func timestampDemo2(timestamp int64) {
	timeObj := time.Unix(timestamp, 0) //Convert timestamp to time format
	fmt.Println(timeObj)
	year := timeObj.Year()     //year
	month := timeObj.Month()   //month
	day := timeObj.Day()       //day
	hour := timeObj.Hour()     //hour
	minute := timeObj.Minute() //minute
	second := timeObj.Second() //second
	fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

3. Time interval

time.Duration is a type defined by the time package. It represents the elapsed time between two time points, in nanoseconds. time.Duration refers to a time interval, and the maximum time period that can be expressed is about 290 years.

The constants of the time interval type defined in the time package are as follows:

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

For example, time.Duration means 1 nanosecond, and time.Second means 1 second.

4. Time operation (Add,Sub,Equal,Before,After)

Add
Required time + interval

func (t Time) Add(d Duration) Time

For example, find the time after one hour:

func main() {
	now := time.Now()
	later := now.Add(time.Hour) // Time after current time plus 1 hour
	fmt.Println(later)
}

Sub
Find the difference between two times:

func (t Time) Sub(u Time) Duration

Return t-u. If the result exceeds the maximum / minimum value that Duration can represent,

To get the time point t-d (d is Duration), use t.Add(-d).

Equal
Judge whether the two times are the same

func (t Time) Equal(u Time) bool

Considering the influence of time zone, the time of different time zone standards can also be compared correctly. This method is not just t==u, but also compares location and time zone information.

Before

If the time point of t is before u, it returns true; Otherwise, false is returned.

func (t Time) Before(u Time) bool

After
If the time point of t is after u, it returns true; Otherwise, false is returned.

func (t Time) After(u Time) bool

5. Timer

Use time. Tick (time interval) to set the timer. The timer is essentially a channel.

func tickDemo() {
	ticker := time.Tick(time.Second) //Define a timer with an interval of 1 second
	for i := range ticker {
		fmt.Println(i)//Tasks executed every second
	}
}

6. Time formatting

The time type has its own Format method. The Format time template in Go language is not the common Y-m-d H:M:S, but uses the birth time of Go at 15:04 on January 2, 2006 (the memory formula is 2006 1 2 3 4).
Add: if you want to format it as 12 hour mode, you need to specify PM. Equivalent to the second half of the day

func formatDemo() {
	now := time.Now()
	// The formatted template is Go's birth time at 15:04 on January 2, 2006 Mon Jan
	// 24-hour system
	fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
	// 12 hour system
	fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan"))
	fmt.Println(now.Format("2006/01/02 15:04"))
	fmt.Println(now.Format("15:04 2006/01/02"))
	fmt.Println(now.Format("2006/01/02"))
}

Time to parse string format

now := time.Now()
fmt.Println(now)
// Load time zone


loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
	fmt.Println(err)
	return
}
// Parses the string time in the specified time zone and format

timeObj, err := time.ParseInLocation("2006/01/02 15:04:05", "2019/08/04 14:15:20", loc)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(timeObj)
fmt.Println(timeObj.Sub(now))

7. Calculate how long the program runs

package main
import (
    "fmt"
    "strconv"
    "time"
)
//Calculate program run time
func test() {
    str := ""
    for i := 0; i < 100000; i++ {
        //Convert int to string
        str += "oldboy" + strconv.Itoa(i)
    }
}
func main() {
    //Timestamp before program start
    start := time.Now().Unix()
    test()
    //Timestamp at the end of the program
    end := time.Now().Unix()
    fmt.Printf("implement test()Function, time consuming%v second\n", end-start)
}

Posted by e39m5 on Tue, 14 Sep 2021 17:15:19 -0700