简体   繁体   English

DateTime格式字符串(无效的格式字符串)

[英]DateTime format string for invalid Format string

I am trying to format Datetime string using 我正在尝试使用格式化日期时间字符串

date.ToString(format)

If user feeds in wrong format, eg "YYYY MM DDr" I would like to know whether I can convert datetime using that format, rather than returning 如果用户输入的格式错误,例如“ YYYY MM DDr”,我想知道是否可以使用该格式转换日期时间,而不是返回

2015 04 DDr

since 以来

DateTime.ToString(format)

always returns a valid String. 始终返回有效的字符串。

For example, is there any method that perhaps throw an exception on failed conversion so that I can catch and decide not display my output string instead of displaying something like 例如,是否有任何方法可能会在转换失败时引发异常,以便我可以捕获并决定不显示我的输出字符串,而是显示类似

2015 04 DDr

If you assume that all the letters inserted in your format are either separators or letters that should be converted to a DatePart, you can check if after converting the date you still have non separator chars that were not converted, as follows: 如果您假设以格式插入的所有字母都是分隔符或应转换为DatePart的字母,则可以检查转换日期后是否仍然存在未转换的非分隔符,如下所示:

public static class DateTimeExtension
    {
        public static string ToStringExt(this DateTime p_Date, String format)
        {
            char[] separators = { ' ', '/', '-' };

            String stringDate = p_Date.ToString(format);

            foreach (char dateChar in format)
            {
                if (stringDate.Contains(dateChar) && !separators.Contains(dateChar))
                {
                    throw new FormatException("Format Error");
                }
            }
            return stringDate;
        }
    }

Edited after @Vladimir Mezentsev observation: 在@Vladimir Mezentsev观察后编辑:

This code assumes that you are converting only to Numbers, if you are doing something that will convert to Day strings like Tuesday, the logic may fail. 此代码假定您仅转换为数字,如果您执行的操作会转换为Day字符串(如Tuesday),则逻辑可能会失败。 To address this scenario the code would get a little more complicated but can also be achieved with something like this: 为了解决这种情况,代码会变得有些复杂,但也可以通过以下方式实现:

public static string ToStringExt(this DateTime p_Date, String format)
{
    foreach (string dateFormatPart in getFormatStrings(format))
    {
        if (p_Date.ToString(dateFormatPart) == dateFormatPart)
        {
            throw new FormatException("Format Error");
        }
    }
    return p_Date.ToString(format);
}

private static IEnumerable<string> getFormatStrings(String format)
{
    char[] separators = { ' ', '/', '-' };
    StringBuilder builder = new StringBuilder();

    char previous = format[0];
    foreach (char c in format)
    {
        if (separators.Contains(c) || c != previous)
        {
            string formatPart = builder.ToString();
            if (!String.IsNullOrEmpty(formatPart))
            {
                yield return formatPart;
                builder.Clear();
            }
        }
        if(!separators.Contains(c))
        {
            builder.Append(c);
        }
        previous = c;
    }
    if (builder.Length > 0)
        yield return builder.ToString();
}

Have a look at https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx . 看看https://msdn.microsoft.com/zh-cn/library/8kb3ddd4(v=vs.110).aspx Particularly this part... 特别是这部分...

在此处输入图片说明

If you're wanting to validate the string used to format the DateTime object, then you'll probably have to write your own using the link provided to know what formats are acceptable, and treat any other characters as errors. 如果要验证用于格式化DateTime对象的字符串,则可能必须使用提供的链接编写自己的字符串,以了解可以接受的格式,并将任何其他字符视为错误。

There is no invalid format, because you can parse formatted string with exact same format. 没有invalid格式,因为您可以解析格式完全相同的字符串。 Even if after parsing you have not loss in any part of date, that could not form the final decision - valid or invalid format. 即使经过解析,您在日期的任何部分都没有丢失,但这不能形成最终决定- validinvalid格式。

You should carefully consider what can be appropriate for user, even give him an opportunity to construct format from some predefined blocks. 您应该仔细考虑哪些内容适合用户,甚至给他机会从一些预定义的块中构建格式。 Maybe show sample conversion with confirmation. 也许显示带有确认的示例转换。

For specific formats you can create some extension method where you can apply your business rules and throw exceptions when you need it. 对于特定格式,您可以创建一些扩展方法,在其中可以应用业务规则并在需要时引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM