c# - 转换日期表示不支持

标签 c#

我正在尝试将日期转换为 yyyyMMdd 格式,但它说支持的日期。

public override object StringToField(string from)
{
        try
        {
            string[] elements = from.Trim().Split(new char[] { ' ' });

            string date = RemoveNonNumericCharacters(elements[0]);

            return DateTime.ParseExact(date,"yyyyMMdd",CultureInfo.InvariantCulture,DateTimeStyles.None);
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("Invalid date: {0}", from));
        }
 }

它只是试图转换它,所以我不明白 05/02/2018 22:28。

The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

编辑 2

显示删除数字字符

private string RemoveNonNumericCharacters(string item)
{
        string result = "";

        foreach (char character in item)
        {
            if (char.IsNumber(character))
            {
                result += character;
            }
        }

        return result;
 }

编辑3

解析前的日期结果:06022018

最佳答案

05/02/2018 不是 yyyyMMdd。您的 RemoveNonNumericCharacters 方法可能会将其转换为 05022018,即 0502 年、20 月、18 天。将您传递给 ParseExact 的字符串格式更改为 ddMMyyyyMMddyyyy(不清楚是哪一个)。

关于c# - 转换日期表示不支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50350189/

相关文章:

c# - 具有相同元素的两个列表不相等。为什么?

c# - Console.WriteLine 与打印

c# - 为什么我的更新无法持续?

c# - 为什么我们需要结构? (C#)

c# - Azure.RequestFailedException : 'Service request failed. 状态 : 404 (The specified blob does not exist. )错误代码:BlobNotFound

c# - 使用 CultureInfo 时 DateTime.Parse 返回错误值

C#如何在字符串中找到多余的 ) 或 ( 括号,并用@替换它们

c# - 将数据放在 cookie 中安全吗?

c# - 获取当前类名包括父类名?

c# - 在 Linq 组中查找最大和最小 DateTime