C#正则表达式 将非标准日期转换成标准日期
/// <summary> /// 将非标准日期修改成标准日期 标准日期 2021-09-01共10位,非标准日期 2021-9-1、2021-09-1、2021-9-01、2021年9月1日、2021年11月1日、2021年9月21日 /// </summary> /// <param name="datetime"></param> /// <returns></returns> public string GetDate(string datetime) { //将年月转换成- if (Regex.IsMatch(datetime, "日")) { datetime = Regex.Replace(datetime, @"\D", "-").ToString().Substring(0, Regex.Replace(datetime, @"\D", "-").ToString().Length - 1); } else { datetime = Regex.Replace(datetime, @"\D", "-").ToString(); } if (datetime.Length == 10) { return datetime; } else { string year = datetime.Substring(0, 4); int index1 = datetime.IndexOf('-', 1); int index2 = datetime.LastIndexOf('-'); string mouth = Regex.Match(datetime, @"-\d{1,2}-").ToString(); //如果月份是3位则中间补0 if (mouth.Length == 3) { mouth = mouth.Substring(1, 1); mouth = "-" + "0" + mouth + "-"; } //获取第二个-后所有的数字 var dayex = Regex.Matches(datetime, @"-\d{1,2}"); //取第二个-后的数字 string day = dayex[1].ToString(); day = day.Substring(1, day.Length - 1); if (day.Length == 1) { day = "0" + day; } datetime = year + mouth + day; return datetime; } }
/// <summary> /// 将非标准时间修改成标准时间06:55 非标准时间 6点3分、6点30分、06点3分、06点13分 /// </summary> /// <param name="time"></param> /// <returns></returns> public string GetTime(string time) { time = Regex.Replace(time, @"\D", ":").ToString().Substring(0, Regex.Replace(time, @"\D", "-").ToString().Length - 1); string hour = Regex.Match(time, @"\d{1,2}:").ToString(); //截取冒号前面的数字 hour = hour.Substring(0, hour.Length - 1); string minute = Regex.Match(time, @":\d{1,2}").ToString(); //截取冒号后面的数字 minute = minute.Substring(1, minute.Length - 1); if (hour.Length == 1) { hour = "0" + hour; } if (minute.Length == 1) { minute = "0" + minute; } time = hour + ":" + minute; return time; }
/// <summary> /// 将非标准时间修改成标准时间06:55 非标准时间 6:5 06:5 6:05 /// </summary> /// <param name="time"></param> /// <returns></returns> public string GetTimer(string hour, string minute) { //截取冒号前面的数字 hour = hour.Substring(0, hour.Length - 1); //截取冒号后面的数字 minute = minute.Substring(1, minute.Length - 1); if (hour.Length == 1) { hour = "0" + hour; } if (minute.Length == 1) { minute = "0" + minute; } string time = hour + ":" + minute; return time; }