c# - 检查给定字符串是否是用于转换 DateTime 的有效格式字符串

标签 c# string validation string-formatting datetime-format

TLDR;

我需要验证给定的输入字符串是否是用于解析日期时间的有效“格式字符串”。例如,

  • yy-mm-dd 有效
  • yy-aaaaaaa123 无效

我正在开发 program它接受日期格式作为用户的输入。下面是我删除的代码

private string datetimeFormat;

public Logger(string dateFormat)
{
    datetimeFormat = dateFormat;
}

...
...
...

// Inside some function
string pretext = $"{DateTime.Now.ToString(datetimeFormat)},{logLevel},";

我需要为 dateFormat 字符串输入添加验证。

我正在考虑在数组中包含许多可能的组合并仅接受这些字符串。但还有其他方法可以验证吗?


更新:

我的输入字符串不包含任何日期。这不是 specified question 的重复项.

This question根本与日期时间无关。

最佳答案

这取决于您所说的“有效”的含义以及您认为“只有 DateTime,没有其他”限制对您的重要性。

以下是我们可以用来测试格式字符串的一些规则,但有一些明确的限制:

  1. 必须适合传递给 DateTime.ToString(string format) 以将 DateTime 值转换为字符串。

  2. 必须能够将规则 1 的输出解析为有效的 DateTime 值。

  3. 规则 2 的输出不得包含时间部分。

  4. (可选)规则 2 的输出应与定义的准确度范围内的输入相同。

只要您期望输出是完全指定的日期,这些对于许多用途来说就足够了。必须注明年、月、日。下面是一些根据这些规则进行测试的代码:

static System.Globalization.CultureInfo DateTimeProvider = System.Globalization.CultureInfo.InvariantCulture;
const System.Globalization.DateTimeStyles ParseExactStyle = System.Globalization.DateTimeStyles.None;
static DateTime[] DateSamples = new[]
    {
        DateTime.Now,
        DateTime.Today,
        DateTime.Today.AddDays(1 - DateTime.Today.Day),
        DateTime.Parse("10-Jan-2000"),
        DateTime.Parse("01-Oct-1990"),
        DateTime.Parse("13-Feb-1901")
    };

public static bool IsValidDateFormat(string format, out string result)
{
    var maxDifference = TimeSpan.FromDays(1);
    foreach (var sample in DateSamples)
    {       
        // Rule 1: Must be suitable for '.ToString(...)'
        string sampleString;
        try
        {
            sampleString = sample.ToString(format);
        }
        catch (FormatException e)
        {
            result = $"Failed rule 1: {e.Message}";
            return false;
        }

        // Rule 2: Must be able to parse the produced string
        if (!DateTime.TryParseExact(sampleString, format, DateTimeProvider, ParseExactStyle, out var parsed))
        {
            result = $"Failed rule 2: does not parse it's own output. '{sampleString}'";
            return false;
        }

        // Rule 3: No time values.
        if (parsed != parsed.Date)
        {
            result = $"Failed rule 3: No time values. '{sampleString}' => #{parsed}#";
            return false;
        }

        // Rule 4: Difference must be less than maxDifference
        TimeSpan difference = sample < parsed ? parsed - sample : sample - parsed;
        if (difference >= maxDifference)
        {
            result = $"Failed rule 4: difference '{difference}' too large.";
            return false;
        }
    }

    result = "OK";
    return true;
}

(这会将 result 输出参数设置为格式字符串失败原因的描述,或者如果通过则确定,但您可能更愿意返回一个简单的枚举值。)

这可以验证各种奇怪的格式,包括那些带有额外的非上下文或至少非时间字符的格式。这些示例包括一些针对时间值、顺序反转等的测试。

但是有一些限制:

  • TryParseExact 不适用于 standard format stringsd、“F”等
  • 它也不适用于 3 位以上数字的年份格式 (yyy) 和其他拉伸(stretch)格式。
  • 这些示例包含一项防止使用 2 位数年份的测试。

简而言之,对于简单的工作来说已经足够了。您可以稍微修剪一下。

关于c# - 检查给定字符串是否是用于转换 DateTime 的有效格式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808236/

相关文章:

c# - 反序列化动态 JSON 文件 C# NewtonSoft.JSON

c# - 如何获取 IObservable<IObservable<T>> 的最新变化事件?

c# - 使用 C# 中的 32feet.net 库将 bMessage 从 Windows 发送到消息访问服务器

c# - 在图像上绘制对比字符串

javascript查询字符串

c# - MS Access 数据库的连接字符串

c# - EF 核心 Web API : foreign key validation

php - Laravel 填充数组元素的验证规则

php - Laravel 中正则表达式规则的自定义验证消息?

c - 如何使用格式化字符串攻击