LoginSignup
4
0

More than 3 years have passed since last update.

GoのDatetime忘れがちなので、まとめてみた

Last updated at Posted at 2020-01-10

普段良く使うtimeメソッドをまとめてみた。

Formatについて

他の言語みたいなYYYY-MM-DD hh:mm:sstimeフォーマット、Goでは↓このように書く
2006-01-02 15:04:05

String -> Time

time.Parse(layout,string)を使って、文字列をTimeオブジェクトにする

例:

    str := "2020-01-09T19:00:00Z"
    t, _ := time.Parse("2006-01-02T15:04:05Z", str) // 出力結果: 2020-01-09 19:00:00 +0000 UTC

Time -> String

    now := time.Now()
    str := now.Format("2006-01-02 15:04:05")

時間の比較

After()メソッドを使う
t1 > t2なら、t1.After(t2) => true
t1 < t2なら、t1.After(t2) => false

    str1 := "2020/01/10 00:00:00"
    str2 := "2020/01/08 00:00:00"

    t1, _ := time.Parse("2006/01/02 15:04:05", str1)
    t2, _ := time.Parse("2006/01/02 15:04:05", str2)

    t1.After(t2)) // 出力結果:true

2つ時刻の差を求める

Sub()メソッドは時間の経過値を求める

    start, _ := time.Parse("2006/01/02 15:04:05", "2020/01/08 00:00:00")
    end, _ := time.Parse("2006/01/02 15:04:05", "2020/01/10 00:00:00")

    duration := end.Sub(start) // 48h0m0s

    days := int(duration.Hours()) / 24
    hours := int(duration.Hours()) % 24
    mins := int(duration.Minutes()) % 60
    secs := int(duration.Seconds()) % 60

    log.Printf("%ddays + %dhours + %dminutes + %dseconds", days, hours, mins, secs) 
    // 2days + 0hours + 0minutes + 0seconds

現在の時間まで経過値を求める

Since()を使う、time.Now().Sub(t)の省略

何日後、何日前の時間を求める

AddDate()を使う
引数には、year,month,dayを渡す

    now := time.Now()

    // 2日後
    after2days := now.AddDate(0, 0, 2) // 2020-01-12 11:56:27

    // 2日前
    before2days := now.AddDate(0, 0, -2) // 2020-01-08 11:57:49

また、何分や何時間前や後は Add()を使うと便利

    // 一時間後
    t := now.Add(1 * time.Hour)

    // 30分後
    t := now.Add(30 * time.Minute)
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0