一个字符串怎么可以校验它可不可以转化为日期型
比如string tt="2005-5-18";就可以转化
而string tt="2005-5-58";就不可以转化.
if(inputdate.Value is DateTime)
{
//do something;
}
else
{
return;
}

解决方案 »

  1.   

    建议自己写一个方法判断,trycatch效率太低。
      

  2.   

    try{
        Convert.ToDateTime(tt)
       }
    catch(Exception)
    {}
      

  3.   

    try,catch效率不低啊。你试试编译成release,异常处理的效率在debug和release中区别超级大。编译成release,很快的。
      

  4.   

    还是觉得正则好些,try catch确实在效率上比较差!呵呵!
      

  5.   

    google 搜索,日期正则表达式
      

  6.   

    不要调试运行,测试如下:
    debug模式:34.7毫秒
    release模式:2.8679毫秒
    这个时间不是很长嘛,这里不是和 闵峰 抬杠,请不要生气。
    我的意思,大家说的用正则是好方法,但是不要都一概认为try,catch速度慢,在编译环境,用debug模式,调试运行,是慢,编译后,非调试模式,直接运行,速度很快的。
      

  7.   

    以下测试代码:
    private void button1_Click(object sender, System.EventArgs e)
    {   
    string str = "aaa";
    CountFunction.CountFunction ct = new CountFunction.CountFunction();
    try
    {
    ct.Start();
    DateTime.Parse(str);
    }
    catch
    {
    ct.Stop();
    MessageBox.Show((ct.Duration*1000).ToString());
    }
    }
    计算时间的类库:
    using System;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.ComponentModel;
    namespace CountFunction
    {
    public class CountFunction
    {#region  DllImport
    [DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceFrequency(out long lpFrequency); [DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
    #endregion#region Declare Variable
    private long startTime,stopTime;
    private long freq;
    #endregion#region Function
    public CountFunction()
    {
    this.startTime = 0;
    this.stopTime = 0;
    if(QueryPerformanceFrequency(out freq) == false) throw new Win32Exception(); }  // 在开始要记录时间的方法
    public void Start()
    {
    Thread.Sleep(0);
    QueryPerformanceCounter(out startTime);
    } // 停止记录时间的方法
    public void Stop()
    {
    QueryPerformanceCounter(out stopTime);
    } // 获取时间差,得到函数执行时间
    public double Duration
    {
    get
    {
    return (double)(stopTime - startTime)/(double)freq;
    }
    }#endregion

    }
    }