2
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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

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)
}

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
2
Help us understand the problem. What are the problem?