private void txtDateEmployed_TextChanged(object sender, EventArgs e) { this.txtDateEmployed.BackColor = Color.White; //当控件失去焦点时 this.txtDateEmployed.LostFocus += new EventHandler(txtInput_LostFocus); } void txtInput_LostFocus(object sender, EventArgs e) { string time = this.txtDateEmployed.Text.Trim(); //如果为空 if (time == "") { //显示当前日期 string now = DateTime.Now.ToLocalTime().ToString("yyyy/MM/dd"); now = now.Replace("-", "/"); this.txtDateEmployed.Text = now; return; } //只有分隔符 if (time.Replace("/", "") == "") { this.txtDateEmployed.Text = ""; return; } //超出日期范围 if (int.Parse(time.Replace("/", "")) < 17530101 || int.Parse(time.Replace("/", "")) > 99991231) { this.txtDateEmployed.Focus(); this.txtDateEmployed.SelectAll(); this.txtDateEmployed.BackColor = Color.Yellow; return; } //检查日期是否合法 if (!CheckDate(time.Replace("/", ""))) { this.txtDateEmployed.Focus(); this.txtDateEmployed.SelectAll(); this.txtDateEmployed.BackColor = Color.Yellow; return; } time = time.Replace("/", ""); //格式化时间 time = time.Insert(4, "/"); time = time.Insert(7, "/"); this.txtDateEmployed.Text = time; this.txtDateEmployed.BackColor = Color.White; } /// <summary> /// 验证日期合法性 /// </summary> /// <param name="date">日期参数</param> /// <returns>是否合法</returns> private bool CheckDate(string date) { try { //取出年月日 int year = int.Parse(date.Substring(0, 4)); int month = int.Parse(date.Substring(4, 2)); int day = int.Parse(date.Substring(6, 2)); int[] days = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (IsLeapYear(year)) { //如果是闰年 days[1] = 29; } return year > 0 && month <= 12 && month > 0 && day <= days[month - 1] && day > 0; } catch { return false; } } /// <summary> /// 判断是否是闰年 /// </summary> /// <param name="year">年份</param> /// <returns>是否是闰年</returns> private bool IsLeapYear(int year) { return (year % 4 == 0 || year % 400 == 0) && (year % 100 != 0); }