LoginSignup
1
0

More than 3 years have passed since last update.

golangで先週の〇〇曜日をtime.Timeで取得するコード

Posted at
type Weekday struct {
    Now time.Time
    Loc *time.Location
}

func (w Weekday) LastWeekOf(weekday time.Weekday) time.Time {
    levellingOffset := int(w.Now.Weekday())
    weekDiff := 7-(int(weekday))

    return time.
        Date(w.Now.Year(), w.Now.Month(), w.Now.Day(), 0, 0, 0, 0, w.Loc).
        AddDate(0, 0, -levellingOffset).
        AddDate(0, 0, -weekDiff)
}

こう使う

package main

import (
    "fmt"
    "time"
)

func main() {   
    now := time.Date(2020, 11, 27, 0, 0, 0, 0, time.UTC)    
    fmt.Println(now.Year(), now.Month(), now.Day())

    w := Weekday{
        Now: now, 
        Loc: time.UTC,
    }   
    r := w.LastWeekOf(time.Monday) // 先週の月曜日を取得する
    fmt.Println(r.Year(), r.Month(), r.Day())
}

結果

2020 November 27
2020 November 16
1
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
1
0