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

 在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;  
}  

}

PS:将某一日期类型,转换为指定的字符串格式(MM大写默认月份,小写默认为分钟)

评论

暂无评论