前些日子看高手代码,关于日期转换这么写的。如果是我不会再在catch中添加其他的转换方法。
还是高手考虑周全啊
//日期转换
public static string GetFormatedDate(string strDate)
{
string formatedDate = strDate;
try
{
formatedDate = Convert.ToDateTime(strDate).ToString("yyyy-MM-dd");
}
catch (FormatException e)
{
try
{
formatedDate = DateTime.ParseExact(strDate, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd");
}
catch
{
return strDate;
}
}
return formatedDate;
}
}
下面调用:是集中可能,执行时的过程不一样,有些不会走catch有些走。
//this.textBox1.Text = GetFormatedDate(this.dateTimePicker1.Value.ToString());//2013/9/23 10:36:14
this.textBox1.Text = GetFormatedDate("20130923");
// this.textBox1.Text = GetFormatedDate("2013/9/23");
// this.textBox1.Text = GetFormatedDate("2013923");
// this.textBox1.Text = GetFormatedDate("2013-9-23");