相对于 PHP 而言,Golang 里面的获取时间应该说是很不方便有木有。因此,特意封装了以下项目中常用到的获取时间相关的函数。

// 时间戳相关
package helpers

import "time"

// 获取当前时间|字符串
func GetTime() string {
    return time.Now().Format("2006-01-02 15:04:05")
}

// 获取当前日期|字符串
func GetDate() string {
    return time.Now().Format("2006-01-02")
}

// 获取相对时间|字符串
func GetRelativeTime(years int, months int, days int) string {
    return time.Now().AddDate(years, months, days).Format("2006-01-02 15:04:05")
}

// 获取当前时间戳|秒
func GetTimestamp() int64 {
    return time.Now().UnixNano() / 1e9
}

// 获取当前时间戳|毫秒
func GetMicroTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}

// 获取相对时间戳|秒
func GetRelativeTimestamp(years int, months int, days int) int64 {
    timeStr := GetRelativeTime(years, months, days)
    timeLocation, _ := time.LoadLocation("Asia/Chongqing")
    timeParse, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, timeLocation)
    return timeParse.Unix()
}

// 获取相对日期[00:00:00]时间戳|秒
func GetZeroTimestamp(years int, months int, days int) int64 {
    timeStr := time.Now().AddDate(years, months, days).Format("2006-01-02 00:00:00")
    timeLocation, _ := time.LoadLocation("Asia/Chongqing")
    timeParse, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, timeLocation)
    return timeParse.Unix()
}

// 时间字符串转时间戳|秒
func TimeToTimestamp(timeStr string) int64 {
    timeLocation, _ := time.LoadLocation("Asia/Chongqing")
    timeParse, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, timeLocation)
    return timeParse.Unix()
}

测试如下:

package main

import (
    "fmt"
    "helpers"
)

func main() {
    fmt.Println(helpers.GetTime()) // 2018-11-06 18:39:08
    fmt.Println(helpers.GetDate()) // 2018-11-06
    fmt.Println(helpers.GetRelativeTime(0, 0, -1)) // 2018-11-05 18:39:08
    fmt.Println(helpers.GetTimestamp()) // 1541500748
    fmt.Println(helpers.GetMicroTimestamp()) // 1541500748857
    fmt.Println(helpers.GetRelativeTimestamp(0, 0, -1)) // 1541414348
    fmt.Println(helpers.GetZeroTimestamp(0, 0, -1)) // 1541347200
    fmt.Println(helpers.TimeToTimestamp("2018-11-06 18:30:00")) // 1541500200
}

标签:Golang