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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
2017-09-02 项目受源代码管理。向源代码管理注册此项目时出错。建议不要对此项目进行任何更改