🦧

Golangの週数判定(アメリカ式)

2022/04/19に公開

1週間の始まりは人それぞれ

1週間の始まりって日曜日からの人と月曜日からという人がいると思う。
1週間の始まりの考え方にはアメリカ式、ヨーロッパ式、中東式があるようです。
アメリカ式: 日曜日始まり
ヨーロッ式: 月曜日始まり
中東式: 土曜日始まり
日本ではアメリカ式とヨーロッパ式が多そうです。

目的

日曜日始まりで週数を取得する必要があった。
Golangで週番号を取得しようとしたら、アメリカ式ではなく、ヨーロッパ式だった。
アメリカ式で週番号を取得して、週数の判定を行う。

アメリカ式週数の判定

main.go
package main

import (
	"fmt"
	"time"
	"math"
)

func main() {
	weekNumber := americanWeekNumber(2022, 4, 19)
	fmt.Println(weekNumber)
}

func americanWeekNumber(year, month, day int) int {
	// 指定した年の日付型作成
	newYearsDay := time.Date(year, time.Month(1), 1, 0, 0, 0, 0, time.Local)
	// 指定した月の日付型作成
	specifiedDate := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local)
	// 曜日取得(1/1の曜日)
	newWeekday := (newYearsDay.Weekday()) % 7
	fmt.Println(newWeekday)
	// 週番号の計算
	// 指定した日の日曜日の日付けを取得
	sundayFirstMonth := newYearsDay.AddDate(0, 0, int(-newWeekday))
	// 1/1の週初めから経過した時間を求める
	week := specifiedDate.Sub(sundayFirstMonth)
	// 時間から週番号を取得する
	weeklyNumber := math.Floor((week.Hours() / 24) / 7)
	return int(weeklyNumber)
}

参考文献

Go 日付処理チートシート
Python アメリカ式の週番号の取得

Discussion