C# 怎么判断一个字符串是不是合法日期

??

很简单

using System;
using System.Timers;
using System.Threading;
class Test
{
static void Main()
{
string mystring = "2007年1月1日";
try
{
DateTime mydate = Convert.ToDateTime(mystring);
Console.WriteLine(mydate);
}
catch
{
Console.WriteLine("不是合法日期");
}
Console.ReadLine();
}
}

如果是web的话
那么可以这么写

protected void Page_Load()
{
string mystring = "2007年1月1日";
try
{
DateTime mydate = Convert.ToDateTime(mystring);
Response.Write(mydate);
}
catch
{
Response.Write("不是合法日期");
}
}

共同学习!
温馨提示:内容为网友见解,仅供参考
第1个回答  2007-12-03
.net 2.0 的话,可以用DateTime.TryParse()方法 页面上还可以加校验控件通过正则表达式进行校验private bool ChkDate(string str) { try { DateTime t1 = DateTime.Parse(str); return true; //返回真 } catch { return false; } }
相似回答