如何在C#中验证日期时间?

问题描述 投票:102回答:11

我怀疑我是唯一提出这个解决方案的人,但是如果你有更好的解决方案,请在这里发布。我只想在这里留下这个问题,以便我和其他人可以在以后搜索。

我需要判断是否在文本框中输入了有效日期,这是我提出的代码。当焦点离开文本框时,我会触发它。

try
{
    DateTime.Parse(startDateTextBox.Text);
}
catch
{
    startDateTextBox.Text = DateTime.Today.ToShortDateString();
}
c# datetime validation
11个回答
245
投票
DateTime.TryParse

我相信这更快,这意味着你不必使用丑陋的尝试/捕获:)

e.g

DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
  // Yay :)
}
else
{
  // Aww.. :(
}

0
投票

您还可以为特定的DateTime定义CultureInfo格式

public static bool IsDateTime(string tempDate)
{
    DateTime fromDateValue;
    var formats = new[] { "MM/dd/yyyy", "dd/MM/yyyy h:mm:ss", "MM/dd/yyyy hh:mm tt", "yyyy'-'MM'-'dd'T'HH':'mm':'ss" };
    return DateTime.TryParseExact(tempDate, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDateValue);
}

-3
投票
DateTime temp;
try
{
    temp = Convert.ToDateTime(grd.Rows[e.RowIndex].Cells["dateg"].Value);
    grd.Rows[e.RowIndex].Cells["dateg"].Value = temp.ToString("yyyy/MM/dd");
}
catch 
{   
    MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
    grd.Rows[e.RowIndex].Cells["dateg"].Value = null;
}

-3
投票
DateTime temp;
try
{
    temp = Convert.ToDateTime(date);
    date = temp.ToString("yyyy/MM/dd");
}
catch 
{
    MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
    date = null;
}

58
投票

不要使用异常进行流量控制。使用DateTime.TryParseDateTime.TryParseExact。我个人更喜欢具有特定格式的TryParseExact,但我猜有时TryParse更好。基于原始代码的示例使用:

DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
    startDateTextox.Text = DateTime.Today.ToShortDateString();
}

更喜欢这种方法的原因:

  • 更清晰的代码(它说它想要做什么)
  • 捕获和吞咽异常的性能更好
  • 这不会不恰当地捕获例外 - 例如OutOfMemoryException,ThreadInterruptedException。 (您当前的代码可以通过捕获相关的异常来修复以避免这种情况,但使用TryParse仍然会更好。)

21
投票

这是解决方案的另一种变体,如果字符串可以转换为DateTime类型,则返回true,否则返回false。

public static bool IsDateTime(string txtDate)
{
    DateTime tempDate;
    return DateTime.TryParse(txtDate, out tempDate);
}

4
投票

我会使用DateTime.TryParse()方法:http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx


3
投票

那么使用TryParse呢?


3
投票

使用DateTime.TryParse的一个问题是它不支持在没有分隔符的情况下输入的日期的非常常见的数据输入用例,例如: 011508

这是一个如何支持这个的例子。 (这是我正在构建的框架,因此它的签名有点奇怪,但核心逻辑应该可用):

    private static readonly Regex ShortDate = new Regex(@"^\d{6}$");
    private static readonly Regex LongDate = new Regex(@"^\d{8}$");

    public object Parse(object value, out string message)
    {
        msg = null;
        string s = value.ToString().Trim();
        if (s.Trim() == "")
        {
            return null;
        }
        else
        {
            if (ShortDate.Match(s).Success)
            {
                s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2);
            }
            if (LongDate.Match(s).Success)
            {
                s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4);
            }
            DateTime d = DateTime.MinValue;
            if (DateTime.TryParse(s, out d))
            {
                return d;
            }
            else
            {
                message = String.Format("\"{0}\" is not a valid date.", s);
                return null;
            }
        }

    }

1
投票
    protected bool ValidateBirthday(String date)
    {
        DateTime Temp;

        if (DateTime.TryParse(date, out Temp) == true &&
      Temp.Hour == 0 &&
      Temp.Minute == 0 &&
      Temp.Second == 0 &&
      Temp.Millisecond == 0 &&
      Temp > DateTime.MinValue)
            return true;
        else
            return false;
    }

//假设输入字符串是短日期格式。 例如“2013/7/5”返回true或 “2013/2/31”返​​回false。 http://forums.asp.net/t/1250332.aspx/1 // bool booleanValue = ValidateBirthday(“12:55”);返回false


1
投票
private void btnEnter_Click(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    //if (!IsValidDOB(maskedTextBox1.Text)) 
    if (!ValidateBirthday(maskedTextBox1.Text))
        MessageBox.Show(" Not Valid");
    else
        MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{ 
    DateTime temp;
    if (DateTime.TryParse(dob, out temp))
        return (true);
    else 
        return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
    DateTime Temp;
    if (DateTime.TryParse(date, out Temp) == true &&
        Temp.Year > 1900 &&
       // Temp.Hour == 0 && Temp.Minute == 0 &&
        //Temp.Second == 0 && Temp.Millisecond == 0 &&
        Temp > DateTime.MinValue)
        return (true);
    else
        return (false);
}

1
投票

所有的答案都很棒但是如果你想使用单一功能,这可能会有效。

private bool validateTime(string dateInString)
{
    DateTime temp;
    if (DateTime.TryParse(dateInString, out temp))
    {
       return true;
    }
    return false;
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.