转--Go时间格式化和类型互换操作

时间:2022-05-04
本文章向大家介绍转--Go时间格式化和类型互换操作,主要内容包括获取本地时间、指定格式的日期字符类型、构造指定时间类型、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

获取本地时间

    // get current timestamp
    currentTime := time.Now().Local()    //print time
    fmt.Println(currentTime)

指定格式的日期字符类型

// get current timestamp
    currentTime := time.Now().Local()
//format Time, string type
    newFormat := currentTime.Format("2006-01-02 15:04:05.000")
    fmt.Println(newFormat)

构造指定时间类型

//build Time 2016-02-17 23:59:59.999, DateTime type
    myTime := time.Date(0162, time.February, 17, 23, 59, 59, 999, time.UTC)

    //output the myTime
    fmt.Println("MyTime:", myTime.Format("2006-01-02 15:04:05.000"))

完整代码:

package main

import (    "fmt"
    "time")

func FormatTime() {
    // get current timestamp
    currentTime := time.Now().Local()

    //print time
    fmt.Println(currentTime)

    //format Time, string type
    newFormat := currentTime.Format("2006-01-02 15:04:05.000")
    fmt.Println(newFormat)


    //build Time 2016-02-17 23:59:59.999, DateTime type
    myTime := time.Date(0162, time.February, 17, 23, 59, 59, 999, time.UTC)

    //output the myTime
    fmt.Println("MyTime:", myTime.Format("2006-01-02 15:04:05.000"))

    //current milliseconds
    fmt.Println("milliseconds:", time.Now().UnixNano()/int64(time.Millisecond))

    //TODO Changing time layout(form)
}

func main(){
FormatTime()
}