简体   繁体   English

C#-System.FormatException:System.DateTime处的格式字符串无效

[英]C# - System.FormatException: Invalid format string at System.DateTime

I am Compairing the date formats and it works fine for dd-MM-yyyy input but throws exception for dd/MM/yyyy . 我正在编译日期格式,它对于dd-MM-yyyy输入工作正常,但是对dd/MM/yyyy抛出异常。

My Code: 我的代码:

string s = Console.ReadLine();
DateTime d = DateTime.ParseExact(s, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string h = d.ToString("dd-MM-yyyy");
if (h.Equals(s))
{
    Console.WriteLine("Valid");
}
else
{
    Console.WriteLine("Invalid");
}

You have specified that DateTime.ParseExact expects date only in "dd-MM-yyyy" format. 您已指定DateTime.ParseExact仅以"dd-MM-yyyy"格式期望日期。 Parsing any other format of date string will throw FormatException as it is specified in Documentation : 解析日期字符串的任何其他格式都会抛出FormatException,如文档中所指定:

FormatException is thrown when s does not contain a date and time that corresponds to the pattern specified in format . 如果s不包含与format中指定的模式相对应的日期和时间,则引发FormatException。

If you want to support several formats, you should provide all of them. 如果要支持多种格式,则应提供所有格式。 That is possible to do with DateTime.ParseExact overload which accepts array of formats: 这可能与DateTime.ParseExact重载有关,该重载接受格式数组:

 var formats = new [] {"dd-MM-yyyy", "dd/MM/yyyy" };
 var d = DateTime.ParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)

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

相关问题 DateTime格式-在C#中获取System.FormatException - DateTime Format - Getting System.FormatException in c# C#System.FormatException:输入字符串的格式不正确 - C# System.FormatException: Input string was not in a correct format System.FormatException:输入字符串的格式不正确。 c# - System.FormatException: Input string was not in a correct format. c# C# 中的 System.FormatException - System.FormatException in C# c# 中的 DateTime 解析:获取“System.FormatException:”String 未被识别为有效的 DateTime”错误 - DateTime parsing in c#:getting a 'System.FormatException: 'String was not recognized as a valid DateTime' error 给定System.FormatException:字符串未被识别为有效的DateTime。 在C#中使用datetime.ParseExact - Giving System.FormatException: String was not recognized as a valid DateTime. using datetime.ParseExact in C# XML可序列化的c#中的DateTime System.FormatException - DateTime System.FormatException in XML Serializable c# System.FormatException:字符串未被识别为有效的DateTime - System.FormatException: String was not recognized as a valid DateTime System.FormatException:字符串未被识别为有效的DateTime - System.FormatException: String was not recognized as a valid DateTime 无法将字符串识别为有效的DateTime(System.FormatException)? - String was not recognized as a valid DateTime(System.FormatException)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM