linux

如何用Go语言获取和处理时间戳

小樊
33
2025-12-29 20:51:42
栏目: 编程语言

在Go语言中,你可以使用time包来获取和处理时间戳。以下是一些常用的方法:

获取当前时间戳

  1. Unix时间戳(秒级)
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    unixTimestamp := now.Unix()
    fmt.Println("Unix timestamp (seconds):", unixTimestamp)
}
  1. Unix时间戳(毫秒级)
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    unixTimestampMillis := now.UnixNano() / int64(time.Millisecond)
    fmt.Println("Unix timestamp (milliseconds):", unixTimestampMillis)
}

将时间戳转换为时间对象

  1. 从Unix时间戳(秒级)转换
package main

import (
    "fmt"
    "time"
)

func main() {
    unixTimestamp := int64(1633072800)
    t := time.Unix(unixTimestamp, 0)
    fmt.Println("Time from Unix timestamp (seconds):", t)
}
  1. 从Unix时间戳(毫秒级)转换
package main

import (
    "fmt"
    "time"
)

func main() {
    unixTimestampMillis := int64(1633072800000)
    t := time.Unix(0, unixTimestampMillis*int64(time.Millisecond))
    fmt.Println("Time from Unix timestamp (milliseconds):", t)
}

格式化时间

你可以使用Format方法来格式化时间对象:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    formattedTime := now.Format("2006-01-02 15:04:05")
    fmt.Println("Formatted time:", formattedTime)
}

解析时间字符串

你可以使用Parse方法来解析时间字符串:

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02 15:04:05"
    timeStr := "2021-10-01 12:34:56"
    t, err := time.Parse(layout, timeStr)
    if err != nil {
        fmt.Println("Error parsing time:", err)
        return
    }
    fmt.Println("Parsed time:", t)
}

示例:获取当前时间的年、月、日、小时、分钟和秒

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    year := now.Year()
    month := now.Month()
    day := now.Day()
    hour := now.Hour()
    minute := now.Minute()
    second := now.Second()

    fmt.Printf("Current time: %d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

通过这些方法,你可以轻松地在Go语言中获取和处理时间戳。

0
看了该问题的人还看了