在C#中的字符串检查日期格式 [英] Checking Date format from a string in C#

查看:137
本文介绍了在C#中的字符串检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查字符串是否包含日期,如 2000年1月1日 2000年10月1日 DD / MM / YYYY 格式。



到目前为止,我已经尝试过这种

 的DateTime dDate; 
dDate = DateTime.Parse(inputString);
的String.Format({0:D / MM / YYYY},dDate);



但我怎么能检查,如果该格式是正确的抛出一个异常


解决方案

 字符串inputString =2000年2月2日 
的DateTime dDate;

如果(DateTime.TryParse(inputString,出dDate))
{
的String.Format({0:D / MM / YYYY},dDate);
}
,否则
{
Console.WriteLine(无效); //< - 控制流转这里
}


I am wanting to check whether a string contains dates such as 1/01/2000 and 10/01/2000 in dd/MM/yyyy format.

So far I have tried this.

 DateTime dDate;
 dDate = DateTime.Parse(inputString);
 String.Format("{0:d/MM/yyyy}", dDate); 

But how can I check if that format is correct to throw an exception?

解决方案

    string inputString = "2000-02-02";
    DateTime dDate;

    if (DateTime.TryParse(inputString, out dDate))
    {
        String.Format("{0:d/MM/yyyy}", dDate); 
    }
    else
    {
        Console.WriteLine("Invalid"); // <-- Control flow goes here
    }

这篇关于在C#中的字符串检查日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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