C# - 如何检查字符串是否仅包含日期 [英] C# - How to check if a string contains ONLY A date

查看:208
本文介绍了C# - 如何检查字符串是否仅包含日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,用户可以在其中输入任何内容。我需要检查用户是否输入了日期。我想要真假。

请建议



谢谢!

I have a text box where a user may enter anything. I need to check if the user entered a date. I want true or false.
Please suggest

Thanks!

推荐答案

使用 TryParse方法 [ ^ ]

Use TryParse method[^]
using System;

public class Program
{
    public static void Main()
    {
          // from your TextBox1.Text
          string TextboxText = "2/22/2014";

          DateTime dt;

          if (DateTime.TryParse(TextboxText, out dt))
          {
               Console.WriteLine("It is a date");
          }
          else
          {
              Console.WriteLine("It is not a date");
          }
    }
}


最好的方式?把它解析为日期:

Best way? Parse it to a date:
DateTime dt;
book isOK = DateTime.TryParse(myTextBox.Text, out dt);


也许最佳解决方案是将其解析为日期。



或者尝试将TextBox更改为MaskedTextBox控件,以便您可以添加允许客户端的日期掩码输入日期格式
Maybe The Best solution is to parse it into date.

Or try to change the TextBox to MaskedTextBox Control so you can add a Date Mask that will allow to the client to enter a date format


这篇关于C# - 如何检查字符串是否仅包含日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆