[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)
解析時間(parse)
// 將 ISO8601 的時間格式轉成 time.Time
time, _ := time.Parse(time.RFC3339, "2020-08-12T07:09:44.975Z")
// 自訂解析的時間格式
// "2006-01-02T15:04:05Z07:00
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
fmt.Println(t)
// Note: 沒有明確定義時區的話,會回傳 UTC 的時間
const shortForm = "2006-Jan-02"
t, _ = time.Parse(shortForm, "2013-Feb-03")
fmt.Println(t)
為解析的時間添加時區資訊:
// 使用 time.LoadLocation 讀取時區
timeZone, _ := time.LoadLocation("Asia/Taipei")
// 建立解析的 layout
const timeLayout = "2006/1/2 15:04"
// 使用 time.ParseInLocation 將時區資訊帶入解析後的時間資訊中
sleepStartTime, _ := time.ParseInLocation(timeLayout, "2020/1/24 13:59", timeZone)
fmt.Println(sleepStartTime) // 2020-01-24 13:59:00 +0800 CST
時間操作:time.Add(), time.AddDate()
使用 t.Add
或 t.AddDate
可以用來操作時間:
/* 操作時間 */
now := time.Now()
afterTwoMinutes := now.Add(time.Minute * 2)
beforeTwoMinutes := now.Add(- time.Minute * 2) // Add 裡面使用負值會變往前推
// now.AddDate(years, months, days)
beforeTwoYears := now.AddDate(-2, 0, 0) // 兩年前
時間比較:time.Before, time.After
使用 t.Before
和 t.After
的方法,可以用來判斷兩個時間的先後順序:
func main() {
now := time.Now()
oneDayAgo := now.AddDate(0, 0, -1)
isOneDayAgoBeforeNow := oneDayAgo.Before(now)
fmt.Println(isOneDayAgoBeforeNow) // true
isOneDayAgoAfterNow := oneDayAgo.After(now)
fmt.Println(isOneDayAgoAfterNow) // false
}
計時器:time.After
每一秒會執行一次:
func main() {
for {
select {
case <-time.After(1 * time.Second):
fmt.Println("one second pass")
}
}
}