やりたいこと
何かと祝日のリストはあると便利(だと思います)。
Google APIを使用しようかと思いましたが、アカウントが必要なので内閣府の祝日リストを使うことにしました。
ここの祝日をListにする
https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html
具体的にはこのcsvを読み取って必要なものだけListに入れる
https://www8.cao.go.jp/chosei/shukujitsu/syukujitsu.csv
鬼のような適当さを見せつけます。
これでとりあえず2020年の12月くらいまで取得できました
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace CleanDuty.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
List<DateTime> holiday = Utility.JapanHoliday.getHoliday();
return View();
}
}
main.csはメソッドを呼び出しているだけ
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
namespace Utility
{
class JapanHoliday
{
public static List<DateTime> getHoliday()
{
string[] JapanHolidayfromCAO = new string[1] { "https://www8.cao.go.jp/chosei/shukujitsu/syukujitsu.csv" };
try
{
WebClient wc = new WebClient();
Stream st = wc.OpenRead(JapanHolidayfromCAO[0]);
StreamReader sr = new StreamReader(st, System.Text.Encoding.GetEncoding("shift-jis"));
List<DateTime> holiday = new List<DateTime>();
int s = 0;
DateTime today = DateTime.Today;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (s == 0) { s++; continue; }
string[] ch = new string[2];
ch = line.Split(',');
DateTime date = DateTime.Parse(ch[0]);
if (today.Year > date.Year)
{
s++; continue;
}
holiday.Add(date);
s++;
}
sr.Close();
st.Close();
return holiday;
}
catch (Exception e)
{
// URLのファイルが見つからない等のエラーが発生
Console.WriteLine("エラーが発生しました\r\n\r\n" + e.ToString());
List<DateTime> holiday = new List<DateTime>();
return holiday;
}
}
}
}
ヘッダーがあるので、ヘッダーはcontinueでスキップしています。
199○年とからあるので、今年の以前のものは排除します。
参考文献
コンソールにいろいろ出すやつ
http://www.katch.ne.jp/~h-inoue/tips/cs/0001.html
streamreaderをListに入れる
http://koshinran.hateblo.jp/entry/2017/
05/31/210543
Webclientは古いらしいので、Httpclientを使うとのこと
https://qiita.com/volpe28v/items/b86e0bc9db8e42688cc3