在Go语言中,你可以使用time包来获取和处理时间戳。以下是一些常用的方法:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
unixTimestamp := now.Unix()
fmt.Println("Unix timestamp (seconds):", unixTimestamp)
}
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
unixTimestampMillis := now.UnixNano() / int64(time.Millisecond)
fmt.Println("Unix timestamp (milliseconds):", unixTimestampMillis)
}
package main
import (
"fmt"
"time"
)
func main() {
unixTimestamp := int64(1633072800)
t := time.Unix(unixTimestamp, 0)
fmt.Println("Time from Unix timestamp (seconds):", t)
}
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语言中获取和处理时间戳。