如何验证DateTime格式?

Kev*_*Cho 19 c# validation datetime

我想让用户输入DateTime格式,但我需要验证它以检查它是否可以接受.用户可以输入"yyyy-MM-dd"并且没问题,但是他们也可以输入"MM/yyyyMM/ddd"或任何其他组合.有没有办法验证这个?

Han*_*s Z 25

你在找这样的东西吗?

DateTime expectedDate;
if (!DateTime.TryParse("07/27/2012", out expectedDate))
{
    Console.Write("Luke I am not your datetime.... NOOO!!!!!!!!!!!!!!");
}
Run Code Online (Sandbox Code Playgroud)

如果您的用户知道所需的确切格式......

string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy" };
DateTime expectedDate;
if (!DateTime.TryParseExact("07/27/2012", formats, new CultureInfo("en-US"), 
                            DateTimeStyles.None, out expectedDate))
{
    Console.Write("Thank you Mario, but the DateTime is in another format.");
}
Run Code Online (Sandbox Code Playgroud)

  • -1 这不是 Mindquake 所要求的。他们想要验证格式字符串,而不是日期字符串。 (3认同)
  • 这只验证特定的日期时间。用户实际上是在输入“格式”本身。 (2认同)
  • 为讨厌的控制台写入+1,因为这是我正在寻找的答案. (2认同)

Jas*_*son 10

我不知道有什么方法可以实际验证他们输入的格式,因为有时候你想要故意包含翻译成任何东西的字符.您可以考虑的一件事是允许用户通过显示其输入格式转换的内容的预览来进行自我验证.


小智 6

我假设您想知道指定的格式字符串是否有效...

为此你可以往返它:

    private bool IsValidDateFormat(string dateFormat)
    {
        try
        {
            String dts=DateTime.Now.ToString(dateFormat);
            DateTime.ParseExact(dts, dateFormat, CultureInfo.InvariantCulture);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)