【C#】验证输入的日期格式
场景描述:输入格式必须满足8:00-9:00;13:00-14:00和2022.01.01;2022.02.02-2022.02.07
#region 校验时间格式 //校验配送时间段格式 try { string[] strs = SendTime.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string str in strs) { string[] times = str.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries); foreach (string time in times) { var temp = Convert.ToDateTime(string.Format("{0} {1}", DateTime.Now.ToString("d"), time)); } } } catch (Exception e) { resultInfo.result = "2"; resultInfo.message = "配送时间段格式不正确"; context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(resultInfo)); return; } //校验不可配送日期 try { string[] strs = UnSendDate.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string str in strs) { string[] dates = str.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries); //验证不可配送日期格式 foreach (string date in dates) { DateTime.ParseExact(date, "yyyy.MM.dd", System.Globalization.CultureInfo.InvariantCulture); } //验证不可配送日期范围 if (dates.Length == 2) { if (Convert.ToDateTime(dates[1].ToString()) < Convert.ToDateTime(dates[0].ToString())) { resultInfo.result = "2"; resultInfo.message = "不可配送截止日期不能小于开始日期"; context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(resultInfo)); return; } } } } catch (Exception e) { resultInfo.result = "2"; resultInfo.message = "不可配送日期格式不正确"; context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(resultInfo)); return; } #endregion