LoginSignup
12
6

More than 5 years have passed since last update.

プレミアムフライデーを求めるメソッドを作った

Last updated at Posted at 2017-02-26

2017年2月24日金曜日から始まったプレミアムフライデー。賛否両論激しいシステムですが、何がともあれ休みが増えることはよいことですね。みなさんは初のプレミアムフライデーは午後3時に退社できましたか? わたしはできませんでした(´・ω・`) 定時退社すらできなかったぜふぁっきん(´・ω・`)

そこで(?)プレミアムフライデーを計算するメソッドを作っておきました。ご活用ください。


import java.util.Calendar;

public class PremiumFridayUtils {

    /**
     * 指定した月のプレミアムフライデーの日を求める。プレミアムフライデーが存在しない月の場合は-1を返す。
     * @param year 年 (1..*)
     * @param month 月 (1..12)
     * @return 指定した月のプレミアムフライデーの日 (1..31)
     */
    public static int getPremiumFriday(int year, int month) {
        // yearは正の数、monthは1以上12以下をそれぞれ満たす必要がある。
        if (year < 1 || month < 1 || month > 12) {
            throw new IllegalArgumentException();
        }

        // プレミアムフライデーの実施は2017年02月以降。
        if (year < 2017 || (year == 2017 && month == 1)) {
            return -1;
        }

        // 対象の月の最終日から1日づつ金曜日かどうか判定し、最初に金曜日と判定された日が
        // その月の最終金曜日=プレミアムフライデーとなる。
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY) {
            calendar.add(Calendar.DATE, -1);
        }

        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static void main(String[] args) {
        // 2017-2019年のプレミアムフライデーを求めて出力する。
        for (int year : new int[]{2017, 2018, 2019}) {
            for (int month = 1; month <= 12; month++) {
                int day = PremiumFridayUtils.getPremiumFriday(year, month);
                if (day != -1) {
                    System.out.printf("%d-%02d-%02d\n", year, month, day);
                }
            }
        }
    }
}
/*
2017-02-24
2017-03-31
2017-04-28
2017-05-26
2017-06-30
2017-07-28
2017-08-25
2017-09-29
2017-10-27
2017-11-24
2017-12-29
2018-01-26
2018-02-23
2018-03-30
2018-04-27
2018-05-25
2018-06-29
2018-07-27
2018-08-31
2018-09-28
2018-10-26
2018-11-30
2018-12-28
2019-01-25
2019-02-22
2019-03-29
2019-04-26
2019-05-31
2019-06-28
2019-07-26
2019-08-30
2019-09-27
2019-10-25
2019-11-29
2019-12-27
*/

12
6
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
12
6