[pkg] time
- Package time @ Golang
- Time Formatting/Parsing @ Go by Example
- Format a time or date @ your basic
/* 建立時間 */
time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
time.Now() // 印出當前時間
time.Now().Hour() // 取得現在是幾點
time.Now().Weekday() // 取得今天是星期幾
time.Now().Weekday() + 2 // 今天是星期幾往後推 2 天
time.Saturday // "Saturday"
/* 時間戳記 */
t := time.Now()
t.Unix() // 1595569527,取得當前時間戳記(秒)
t.UnixNano() // 1595569527112747000,取得當前時間戳記(微秒)
/* 操作時間 */
now := time.Now()
afterTwoMinutes := now.Add(time.Minute * 2)
beforeTwoMinutes := now.Add(- time.Minute * 2) // Add 裡面使用負值會變往前推
// 如果需要帶入變數,需要使用 time.Duration() 將變數轉成 duration
tokenExpireAt = time.Now().Add(time.Hour * time.Duration(expireHours))
// now.AddDate(years, months, days)
beforeTwoYears := now.AddDate(-2, 0, 0)
/* 取得 UTC 時間 */
time.Now().UTC()
/* Format */
afterTwoMinutes.Format(time.RFC3339)) // 也就是 ISO8601 的 format,2009-11-10T23:00:00Z
afterTwoMinutes.Format(http.TimeFormat) // http-date format
時間轉換
time.Unix(<unix>, 0)
把 unix timestamp 轉成 time.Time<time.Time>.Unix()
把 time.Time 轉成 unix timestamp
將時間戳記(timestamp)轉成 time.Time 型別
Convert Unix TimeStamp to time.Time in Go (Golang) @ Golang By Example:將時間戳記轉為時間格式
// 因為 time.Unix 只接收 int64 作為參數,所以要先轉型
timestamp, _ := strconv.ParseInt("1597215563", 10, 64)
time := time.Unix(timestamp, 0)