0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ひさしぶりのプレミアムフライデー(GO言語)

Last updated at Posted at 2018-11-30

はじめに

気づけば今日はプレミアムフライデーです(死語?)
せっかくなので久しぶりにプレミアムフライデーを求める処理を書いてみます。

コード

メイン

main.go
package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {
	r := GetPremiumFriday(2018, 10)
	fmt.Println(r)
}

func GetPremiumFriday(year int, month int) time.Time {
	l := time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.UTC)
	w := l.Weekday()
	dh := strconv.Itoa(int(-(w+2)%7) * 24)
	d, _ := time.ParseDuration(dh + "h")
	return l.Add(d)
}

解説

あまり説明もないですがtimeパッケージを使っています。
time.Date関数の引数部分にある日付部分に0を渡すことで前月の末日が設定されます。
なので受け取った月+1を設定して設定した月の末日を取得しました。

ParseDurationへ文字列で期間を渡すことで、シンプルに日付の減算が可能なのですが、
最大単位がHourのようなのでちょこっとだけ計算を行っています。

テスト

せっかく標準でテスト機構が備わっているのでどんどん使っていきましょう!
VSCodeだとコード上でrun testできるのでこういう時すごく便利です

main_test.go
package main

import (
	"testing"
)

type Fixture struct {
	Yaer      int
	Month     int
	ExpectDay int
}

var fixtures = []Fixture{
	Fixture{2016, 2, 26},
	Fixture{2018, 9, 28},
	Fixture{2018, 10, 26},
	Fixture{2018, 11, 30},
	Fixture{2018, 12, 28},
	Fixture{2019, 1, 25},
}

func TestGetPremiumFriday(t *testing.T) {
	for _, f := range fixtures {
		d := GetPremiumFriday(f.Yaer, f.Month).Day()
		if d != f.ExpectDay {
			t.Error(f)
		}
	}
}

 まとめ

やってみたかっただけでした
そのうちシャイニングマンデーもやるかな

おしまい

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?