C# 將datatime型別轉為Cron
阿新 • • 發佈:2020-10-28
/// <summary> /// datetime修改為corn表示式用於自動預測 /// </summary> /// <param name="time"></param> /// <returns></returns> public string DatetimeToCron(string time,string Week) { var cronValue = ""; string weekCron = "? * *"; try { switch (Week) { case "星期一": weekCron = "? * 2"; break; case "星期二": weekCron = "? * 3"; break;case "星期三": weekCron = "? * 4"; break; case "星期四": weekCron = "? * 5"; break; case "星期五": weekCron = "? * 6"; break;case "星期六": weekCron = "? * 7"; break; case "星期日": weekCron = "? * 1"; break; } if (string.IsNullOrWhiteSpace(time)) return ""; string error = "傳入的時間值[" + time + "]格式有誤!"; int ss = 0, mi = 0, hh = 0; if (time.Length < 5) throw new Exception(error); if (time.Substring(2, 1) != ":") throw new Exception(error); if (!int.TryParse(time.Substring(0, 2), out hh)) throw new Exception(error); if (!int.TryParse(time.Substring(3, 2), out mi)) throw new Exception(error); if (time.Length > 5) { if (time.Substring(5, 1) != ":") throw new Exception(error); if (!int.TryParse(time.Substring(6), out ss)) throw new Exception(error); } if (ss > 59) throw new Exception(error); if (mi > 59) throw new Exception(error); if (hh > 23) throw new Exception(error); cronValue = ss + " " + mi + " " + hh + " " + weekCron; } catch (Exception e) { LogHelper.WriteLog("datetime修改為corn表示式用於自動預測", e); } return cronValue; }