7
8

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.

C# : ソシャゲで使える曜日限定区分サンプル

Posted at

用途

  • 曜日限定のマスタデータを定義する場合に1レコードで管理できる
ID Caption Dow
1 火曜限定   2
2 土日曜限定   96
※Dow = DayOfWeek

ルール

0 1 2 4 8 16 32 64
指定なし 月曜 火曜 水曜 木曜 金曜 土曜 日曜
  • 土曜日を定義したい場合は 32 になる
  • 土曜と日曜日を定義したい場合は 96 (32+64)になる
  • 月曜と水曜と金曜日を定義したい場合は 21 (1+4+16)になる
  • ビット演算を利用して曜日の組み合わせを 0~127 の数値で定義することができる(但し0と127は同じ結果)

チェック処理

Program.cs
using System;

public class Program{
    public static void Main(){
        Console.WriteLine(string.Format("MasterData({0}) is Saturday? {1}", 1, isDayOfWeek(1) ? "yes" : "no"));
        Console.WriteLine(string.Format("MasterData({0}) is Saturday? {1}", 32, isDayOfWeek(32) ? "yes" : "no"));
        Console.WriteLine(string.Format("MasterData({0}) is Saturday? {1}", 34, isDayOfWeek(34) ? "yes" : "no"));
        Console.WriteLine(string.Format("MasterData({0}) is Saturday? {1}", 64, isDayOfWeek(64) ? "yes" : "no"));
        Console.WriteLine(string.Format("MasterData({0}) is Saturday? {1}", 127, isDayOfWeek(127) ? "yes" : "no"));
    }

    /// <summary>対象日チェック処理</summary>
    /// <param name="dow">DayOfWeekFlg</param>
    /// <returns>True:Target, False:Non Target</returns>
    static bool isDayOfWeek(int dow)
    {
        if (dow == 0) return true;
        return (dow & 1 << (DateTime.Now.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)DateTime.Now.DayOfWeek - 1)) == 0 ? false : true;
    }
}

実行結果(土曜日に実行した場合)

MasterData(1) is Saturday? no
MasterData(32) is Saturday? yes
MasterData(34) is Saturday? yes
MasterData(64) is Saturday? no
MasterData(127) is Saturday? yes

数値を曜日に変更するサンプル

Program.cs
using System;
using System.Collections.Generic;

public class Program{
    public static void Main(){
        for (int i = 1; i < 127; i++)
        {
            Console.WriteLine(string.Format("{0} : {1}", i, nameDayOfWeek(i)));
        }
    }

    static string nameDayOfWeek(int dow)
    {
        List<string> ret = new List<string>();
        if ((dow & 1) == 1) ret.Add("月");
        if ((dow & 2) == 2) ret.Add("火");
        if ((dow & 4) == 4) ret.Add("水");
        if ((dow & 8) == 8) ret.Add("木");
        if ((dow & 16) == 16) ret.Add("金");
        if ((dow & 32) == 32) ret.Add("土");
        if ((dow & 64) == 64) ret.Add("日");
        return string.Join(".", ret);
    }
}

実行結果

  1 : 月
  2 : 火
  3 : 月,火
  4 : 水
  5 : 月,水
   ...
124 : 水,木,金,土,日
125 : 月,水,木,金,土,日
126 : 火,水,木,金,土,日
127 : 月,火,水,木,金,土,日
7
8
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?