在C#中,對格式的判斷有一類專門函數,那就是TryParse。TryParse在各個不同的類型類(如int,string,DateTime)中,都是存在的。在TryParse中一般有兩個參數,一個是待判斷的字符串,另外一個是轉換后的結果保存變量。
1:判斷字符串內容是否為日期格式,並返回一個日期變量。
string BeginDate = "2020-7-22"; DateTime dtDate; if (DateTime.TryParse(strDate, out dtDate)) { Console.WriteLine("是正確的日期格式類型"+dtDate); } else { throw new Exception("不是正確的日期格式類型!"); }
2:使用Parse函數判斷字符串內容是否為日期格式。
public bool IsDate(string strDate) { try { DateTime.Parse(strDate); //不是字符串時會出現異常 return true; } catch { return false; } }
在JS中判斷字符串是否為日期格式:
1:使用正則表達式匹配判斷
var BeginDate="2020-07-23"; var r = new RegExp("^[1-2]\\d{3}-(0?[1-9]||1[0-2])-(0?[1-9]||[1-2][1-9]||3[0-1])$")//此表達式可判斷輸入的日期格式為“2020-07-23”或者"2020/07/23"; if (r.test(BeginDate) == false) { alert("開始時間日期格式錯誤"); return false; } else { return true; }
2:使用isNaN轉換判斷
var BeginDate= “2020-07-23”; //isNaN(BeginDate)返回為false則是日期格式;排除data為純數字的情況(此處不考慮只有年份的日期,如‘2020) if(isNaN(BeginDate)&&!isNaN(Date.parse(BeginDate))){ alert("BeginDate是日期格式!") return true; }else{ alert("BeginDate不是日期格式"); }
PS:將某一日期類型,轉換為指定的字符串格式(MM大寫默認月份,小寫默認為分鍾)
textBox.text =strDate.ToString("yyyy-MM-dd hh:mm:ss");