Golang Time Operation & JSON Serialization and Deserialization

Time operation

Time Package

  1. Get the current time
    t := time.Now()
    fmt.Printf("%T\n", t)   //time.Time
    fmt.Println(t)          //2019-07-08 15:23:55.1114609 +0800 DST m=+0.000192401
  1. Gets the specified time
    t := time.Date(2009, 7, 15, 16, 30, 28, 0, time.Local)
    fmt.Println(t)              //2009-07-15 16:30:28 +0800 DST
  1. Time to String
    t := time.Date(2009, 7, 15, 16, 30, 28, 0, time.Local)
    s1 := t.Format("2006 January 2, 15, 2001:04:05")
    fmt.Println(s1)              //16:30:28 July 15, 2009
    s2 := t.Format("2006-1-2 15:04:05")
    fmt.Println(s2)             //2009-7-15 16:30:28
    s3 := t.Format("2006/01/02")
    fmt.Println(s3)             //2009/07/15
  1. String Conversion Time
s = "2019 October 10, 2001"
t, err := time.Parse("2006 January 2, 2001", s)
if err != nil {
    fmt.Println("err:", err)
}
fmt.Println(t)                  //2019-10-10 00:00:00 +0000 UTC
fmt.Printf("%T\n", t)           //time.Time
  1. Get the specified content based on the current time
    t := time.Now()
    year, month, day := t.Date()
    fmt.Println(year, month, day)   //2019 July 8

    hour, min, sec := t.Clock()
    fmt.Println(hour, min, sec)     //15 50 12

    years := t.Year()
    fmt.Println("year", years)        //Year 2019
    fmt.Println(t.YearDay())        //189 How many days is the current date in the year
    months  := t.Month()
    fmt.Println("month", months)       //Month July
    days := t.Day()
    fmt.Println("day", days)         //Day 8
    hours := t.Hour()
	fmt.Println("time", hours)          //15
    minutes := t.Minute()
	fmt.Println("branch", minutes)        //59
    seconds := t.Second()
	fmt.Println("second", seconds)        //18
    nanoseconds := t.Nanosecond()
	fmt.Println("nanosecond", nanoseconds)  //462754000
    weekday := t.Weekday()
	fmt.Println("week",weekday)       //Monday
  1. Timestamp (time difference of 0:0 minutes and 0 seconds from January 1, 1970)
    t1 := time.Date (1970, 1, 1, 1, 0, 0, 0, time.UTC)
    fmt.Println(t1.Unix())                  //3600 (difference in seconds)
    t2 := time.Now()
    fmt.Println(t2.Unix())                  //1562573562

    fmt.Println(t1.UnixNano())              //3600000000000
    fmt.Println(t2.UnixNano())              //1562573562116878000
  1. time interval
t1 := time.Now()
t2 := t1.Add(time.Minute)
fmt.Println(t1)                             //2019-07-08 16:17:46.4768441 +0800 DST m=+0.000175701
fmt.Println(t2)                             //2019-07-08 16:18:46.4768441 +0800 DST m=+60.000175701
fmt.Println(t1.Add(24 * time.Hour))         //2019-07-09 16:17:46.4768441 +0800 DST m=+86400.000175701

t3 := t1.AddDate(1, 0, 0)
fmt.Println(t3)                             //2020-07-08 16:19:42.9320107 +0800 DST

d := t2.Sub(t1)
fmt.Println(d)                              //1m0s
  1. sleep
time.Sleep(3 * time.Second)                 //Program sleeps for 3 seconds

//Sleep Random Number
rand.Seed(time.Now().UnixNano())
randNum := rand.Intn(10) + 1
fmt.Println(randNum)
time.Sleep(time.Duration(randNum) * time.Second)
fmt.Println(randNum)

JSON Serialization and Deserialization

JSON

JSON (JavaScript Object Notation) is a lightweight data exchange format. https://www.json.cn/

  • Rule of grammar
    In the JS language, everything is an object. Therefore, any supported type can be represented by JSON.
  • Key/Value Pairs
    JSON key-value pairs are a way to save JS objects. The key names in a key/value pair combination are written in front and wrapped in double quotes'', using a colon: delimited, followed by the value
    {"firstName": "Json"}
  • Serialization of json
    json serialization refers to the serialization of data types (such as structs, map s, slices) of key-value structures into json strings.
  1. Structural json serialization:
    type Monster struct {
        Name string
        Age int
        Birthday string
        Sal float64
        Skill string
    }

    func main() {
        monster := Monster{
            Name :"Bull Devil",
            Age : 500 ,
            Birthday : "2011-11-11",
            Sal : 8000.0,
            Skill : "Bovine Fist",
        }

        //Serialize monster
        data, err := json.Marshal(&monster) //..
        if err != nil {
            fmt.Printf("Serial number error err=%v\n", err)
        }
        //Output serialized results
        fmt.Printf("monster After serialization=%v\n", string(data))
    }
  1. Mapjson serialization:
    func main() {
        //Define a map
        var a map[string]interface{}
        //With map, make is required
        a = make(map[string]interface{})
        a["name"] = "Red Child"
        a["age"] = 30
        a["address"] = "Hongyacave"

        //Serialize a map
        //Serialize monster
        data, err := json.Marshal(a)
        if err != nil {
            fmt.Printf("Serialization error err=%v\n", err)
        }
        //Output serialized results
        fmt.Printf("a map After serialization=%v\n", string(data))
    }
  1. Slice json serialization:
    func main() {
        var slice []map[string]interface{}
        var m1 map[string]interface{}
        //Before using map, make first
        m1 = make(map[string]interface{})
        m1["name"] = "jack"
        m1["age"] = "7"
        m1["address"] = "Beijing"
        slice = append(slice, m1)

        var m2 map[string]interface{}
        //Before using map, make first
        m2 = make(map[string]interface{})
        m2["name"] = "tom"
        m2["age"] = "20"
        m2["address"] = [2]string{"Mexico","Hawaii"}
        slice = append(slice, m2)

        //Serialize slices
        data, err := json.Marshal(slice)
        if err != nil {
            fmt.Printf("Serialization error err=%v\n", err)
        }
        //Output serialized results
        fmt.Printf("slice After serialization=%v\n", string(data))
        
    }
  1. Basic data type serialization

Serialization of basic data types does not make much sense

    func main() {
        var num1 float64 = 2345.67

        //Serialize num1
        data, err := json.Marshal(num1)
        if err != nil {
            fmt.Printf("Serialization error err=%v\n", err)
        }
        //Output serialized results
        fmt.Printf("num1 After serialization=%v\n", string(data))
    }

Matters needing attention
For struct serialization, if we want the name of the serialized key to be redesigned by ourselves, we can assign a tag tag to the struct.

type Monster struct {
	Name string `json:"monster_name"` //Reflection mechanism
	Age int `json:"monster_age"`
	Birthday string `json:"monster_birthday"`
	Sal float64 `json:"monster_sal"`
	Skill string `json:"monster_skill"`
}

func testStruct() {
	//Demonstration
	monster := Monster{
		Name :"Bull Devil",
		Age : 500 ,
		Birthday : "2011-11-11",
		Sal : 8000.0,
		Skill : "Bovine Fist",
	}

	//Serialize monster
	data, err := json.Marshal(&monster) //..
	if err != nil {
		fmt.Printf("Serial number error err=%v\n", err)
	}
	//Output serialized results
	fmt.Printf("monster After serialization=%v\n", string(data))

}
  • json deserialization
    json deserialization refers to the operation of deserializing a json string into its corresponding data type (such as structure, map, slice)
  1. json deserialization structure:
    type Monster struct {
        Name string  
        Age int 
        Birthday string //....
        Sal float64
        Skill string
    }

    //Demonstrates deserializing a json string into a struct
    func main() {
        //Describes that str is acquired through network transmission in project development.. Or read the file to get it
        str := "{\"Name\":\"Bull Devil~~~\",\"Age\":500,\"Birthday\":\"2011-11-11\",\"Sal\":8000,\"Skill\":\"Bovine Fist\"}"

        //Define a Monster instance
        var monster Monster

        err := json.Unmarshal([]byte(str), &monster)
        if err != nil {
            fmt.Printf("unmarshal err=%v\n", err)
        }
        fmt.Printf("After Deserialization monster=%v monster.Name=%v \n", monster, monster.Name)
    }
  1. json deserialized map:
func main() {
	str := "{\"address\":\"Hongyacave\",\"age\":30,\"name\":\"Red Child\"}"
	//Define a map
	var a map[string]interface{} 

	//Deserialize
	//Note: Deserializing the map does not require make because the make operation is encapsulated in the Unmarshal function
	err := json.Unmarshal([]byte(str), &a)
	if err != nil {
		fmt.Printf("unmarshal err=%v\n", err)
	}
	fmt.Printf("After Deserialization a=%v\n", a)

}
  1. json deserialized slices:
    func main() {
        str := "[{\"address\":\"Beijing\",\"age\":\"7\",\"name\":\"jack\"}," + 
            "{\"address\":[\"Mexico\",\"Hawaii\"],\"age\":\"20\",\"name\":\"tom\"}]"
        
        //Define a slice
        var slice []map[string]interface{}
        //Deserialization, make is not required, because make operations are encapsulated in Unmarshal functions
        err := json.Unmarshal([]byte(str), &slice)
        if err != nil {
            fmt.Printf("unmarshal err=%v\n", err)
        }
        fmt.Printf("After Deserialization slice=%v\n", slice)
    }

Tags: Go

Posted by dr_overload on Thu, 19 May 2022 20:50:19 +0300