C# & JS 判断字符串是否为日期格式

  在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");
原文地址:https://www.cnblogs.com/Jack-Cheng008/p/13362067.html