LoginSignup
3
2

More than 5 years have passed since last update.

Golangでプレミアムフライデーかどうか判定する

Posted at

PHPでプレミアムフライデーかどうか判定する のGolang版。

Goは日付の扱いが難しいですね。もっといい方法がありそうです。

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(IsPremiumFriday("2017-02-24")) // true
    fmt.Println(IsPremiumFriday("2017-02-25")) // false
    fmt.Println(IsPremiumFriday("2017-03-31")) // true
    fmt.Println(IsPremiumFriday("2017-12-29")) // true

}

// IsPremiumFriday returns bool
func IsPremiumFriday(datestr string) bool {

    // 入力日付
    d1, err := time.Parse("2006-01-02", datestr)
    if err != nil {
        return false
    }

    // 翌月の初日を得る
    d2 := d1.AddDate(0, 1, 0)
    d2 = time.Date(d2.Year(), d2.Month(), 1, 0, 0, 0, 0, time.UTC)

    // 一日ずつ減らして最初の金曜日を設定
    for d2.Weekday() != time.Friday {
        d2 = d2.AddDate(0, 0, -1)
    }

    return d1.Equal(d2)
}
3
2
4

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
3
2