Golang Convert Date to Time Example

In Go language, you can use the Parse function provided by the time package to convert a date string into a time type. An example is shown below:

package main

import (
    "fmt"
    "time"
)

func main() {
    dateStr := "2022-01-01"
    layout := "2006-01-02"
    
    t, err := time.Parse(layout, dateStr)
    if err != nil {
        fmt.Println("日期转换错误:", err)
        return
    }
    
    fmt.Println("日期转换成功:", t)
}

In the example above, we utilized the Parse function in the time package to convert the date string “2022-01-01” into a time type, specifying the date format as “2006-01-02”. If there is an error during the conversion, it will print out an error message; if the conversion is successful, it will print the converted time.

bannerAds