C# 如何验证日期时间格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11696060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:52:57  来源:igfitidea点击:

How to validate DateTime format?

c#validationdatetime

提问by Kevin Cho

I am suppose to let the user enter a DateTime format, but I need to validate it to check if it is acceptable. The user might enter "yyyy-MM-dd" and it would be fine, but they can also enter "MM/yyyyMM/ddd" or any other combination. Is there a way to validate this?

我假设让用户输入 DateTime 格式,但我需要验证它以检查它是否可以接受。用户可能输入“yyyy-MM-dd”就可以了,但他们也可以输入“MM/yyyyMM/ddd”或任何其他组合。有没有办法验证这一点?

采纳答案by Jason

I don't know of any way to actually validate the format they enter since sometimes you want to intentionally include characters that translate into anything. One thing you might consider is allowing the user to self validate by showing a preview of what their entered format translates into.

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

回答by Hans Z

Are you looking for something like this?

你在寻找这样的东西吗?

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

If your user knows the exact format(s) needed...

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

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.");
}

回答by Guvante

Unless I am remembering incorrectly, the only invalid DateTime format strings are one character long. You can assume any 2 or more character DateTime format string is valid.

除非我记错了,唯一无效的 DateTime 格式字符串是一个字符长。您可以假设任何 2 个或更多字符的 DateTime 格式字符串都是有效的。

DateTime.ParseExact("qq", "qq", null) == DateTime.Today
DateTime.ParseExact("myy", "501", null) == "05/01/2001"

Standard (1 character)
Custom (>1 character)

标准(1 个字符)
自定义(>1 个字符)

For reference, allowed single character strings as formats:

作为参考,允许使用单个字符串作为格式:

d,D,f,F,g,G,m,M,o,O,r,R,s,T,u,U,y,Y

Any other character, such as q, by itself is invalid. All other strings will be successfully parsed as formatting strings.

任何其他字符,例如q, 本身都是无效的。所有其他字符串将被成功解析为格式化字符串。

回答by Diego De Vita

You don't talk about your validation strategy. Anyway you should use something involving regular expressions and than apply allowed patterns. This would help against the formal validity .. then you have to take care about the actual contents and be sure the values are correct according as month, day and year.

你不会谈论你的验证策略。无论如何,您应该使用涉及正则表达式的东西,而不是应用允许的模式。这将有助于对抗形式有效性.. 然后您必须注意实际内容并确保值根据月、日和年是正确的。

Anyway several people suggested to use the DateTime.TryParse() method to let the substrate take care for you. But you'll have to specify the format anyway! so there's no magic! you would fall in ambiguity otherwise

无论如何,有几个人建议使用 DateTime.TryParse() 方法让基板照顾你。但是无论如何您都必须指定格式!所以没有魔法!否则你会陷入歧义

回答by ZipXap

I assume you want to know if the specified format string is valid...

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

For this you could round-trip it:

为此,您可以往返:

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

回答by Aleksandr Khomenko

My solution was to mark the input-field as read-only and allow users to change the value only by jqueryui datepicker.

我的解决方案是将输入字段标记为只读,并允许用户仅通过jqueryui datepicker更改值。

It is intuitive. You can specify your preferred format and need only to validate this one format.

这是直观的。您可以指定首选格式,并且只需要验证这一种格式。

回答by akash singh

This works for me-

这对我有用-

try
{
  String formattedDate = DateTime.Now.ToString(dateFormat);
  DateTime.Parse(formattedDate);
  return true;
}
catch (Exception)
{
  return false;
}