判断日期是工作日还是节假日

通过API(http://www.easybots.cn/holiday_api.net)获取返回信息

写一个接收的反馈的函数IsHoliday

public string IsHoliday(string date)
        {
            string url = @"http://www.easybots.cn/api/holiday.php?d=";
            url = url + date;
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Timeout = 2000;
            httpRequest.Method = "GET";
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
            string result = sr.ReadToEnd();
            result = result.Replace("
", "").Replace("
", "").Replace("	", "");
            int status = (int)httpResponse.StatusCode;
            sr.Close();
            return result;
        }
节假日函数

根据API,可以发现返回的内容有以下三种
{"20130101":"2"}

{"20130103":"1"}

{"20130201":0}

由于我们只需要判断是否为工作日,因此需要判断两种,即为0或者不为0。

为0的情况不存在“”,1和2存在“”,这个要注意

通过最简单的字段截取方式

substring(s.length-2,1);

判断截取的字段是否为0,就可以了

然后给datepicker控件写一个MouseLeave事件

private void DP_MouseLeave(object sender, MouseEventArgs e)
        {
            string date = Convert.ToDateTime(DP.Text.ToString()).ToString("yyyyMMdd");
            string num = IsHoliday(date).Substring(IsHoliday(date).Length-2, 1);
            switch(num)
            {
                case "0":
                    TB.Text = "工作日";
                    break;
                default:
                    TB.Text = "节假日";
                    break;
            }
        }        
时间控件的离开事件

效果图如下

当然了,前两天新闻说的北京11月7日到12日部分单位放假,这个是不支持的。

原文地址:https://www.cnblogs.com/ZXdeveloper/p/4018886.html