🕒
go言語 timeパッケージの基本まとめ
現在時刻の取得
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Println(t)
}
実行結果
2022-02-21 20:19:35.4769876 +0900 JST m=+0.002378401
任意時間の取得
LoadLocation 公式ドキュメント
ParseInLocation 公式ドキュメント
package main
import (
"fmt"
"time"
)
func main() {
//タイムゾーンの設定
loc, _ := time.LoadLocation("Asia/Tokyo")
t, _ := time.ParseInLocation("2006-01-02", "2022-01-02", loc)
fmt.Println(t)
}
time.ParseInLocation第1引数で使える書き方
Year: "2006" "06"
Month: "Jan" "January"
Textual day of the week: "Mon" "Monday"
Numeric day of the month: "2" "_2" "02"
Numeric day of the year: "__2" "002"
Hour: "15" "3" "03" (PM or AM)
Minute: "4" "04"
Second: "5" "05"
AM/PM mark: "PM"
時間の加算・減算
秒・分・時間の加算・減算
Add公式ドキュメント
package main
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("Asia/Tokyo")
t, _ := time.ParseInLocation("2006-01-02", "2022-01-02", loc)
fmt.Println("-5s", t.Add(time.Second*-5))
fmt.Println("+5s", t.Add(time.Second*5))
fmt.Print("\n")
fmt.Println("-5m", t.Add(time.Minute*-5))
fmt.Println("+5m", t.Add(time.Minute*5))
fmt.Print("\n")
fmt.Println("-5h", t.Add(time.Hour*5))
fmt.Println("+5h", t.Add(time.Hour*-5))
}
日・月・年の加算
AddDate公式ドキュメント
package main
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("Asia/Tokyo")
t, _ := time.ParseInLocation("2006-01-02", "2022-01-02", loc)
fmt.Println("-1d", t.AddDate(0, 0, -1))
fmt.Println("+1d", t.AddDate(0, 0, 1))
fmt.Print("\n")
fmt.Println("-1m", t.AddDate(0, -1, 0))
fmt.Println("+1m", t.AddDate(0, 1, 0))
fmt.Print("\n")
fmt.Println("-1y", t.AddDate(-1, 0, 0))
fmt.Println("+1y", t.AddDate(1, 0, 0))
}
実行結果
-1d 2022-01-01 00:00:00 +0900 JST
+1d 2022-01-03 00:00:00 +0900 JST
-1m 2021-12-02 00:00:00 +0900 JST
+1m 2022-02-02 00:00:00 +0900 JST
-1y 2021-01-02 00:00:00 +0900 JST
+1y 2023-01-02 00:00:00 +0900 JST
時刻の文字出力
package main
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("Asia/Tokyo")
t, _ := time.ParseInLocation("2006-01-02", "2022-01-02", loc)
fmt.Println(t.Format(time.RFC3339))
fmt.Println(t.Format("2006-01-02"))
fmt.Println(t.Format("2006-01-02 03:04:05"))
}
実行結果
2022-01-02T00:00:00+09:00
2022-01-02
2022-01-02 12:00:00
Discussion