c# - 解析字符串输入 C#

标签 c# parsing formatting

假设我有一个绑定(bind)到控制台输入的字符串,并且必须包含以下任何格式的日期数据:

"dd/mm/yyyy"
"dd.mm.yyyy"
"dd,mm,yyyy"

将此字符串解析为 DateTime 对象的最安全方法是什么?我应该使用 Regex 方法还是简单地迭代 String.Format() 方法以及上面提到的所有可能的输入格式,直到它成功解析?

最佳答案

DateTime.ParseExact确实有一个重载,您可以为其提供多种格式

Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

CultureInfo.InvariantCulture 传递给 IFormatProvider 应该为 正确处理分隔符。 , /

var dateformats = new[] { "dd/mm/yyyy", "dd.mm.yyyy", "dd,mm,yyyy" };

DateTime.ParseExact("23/04/2015", dateformats, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact("23.04.2015", dateformats, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact("23,04,2015", dateformats, CultureInfo.InvariantCulture, DateTimeStyles.None);

关于c# - 解析字符串输入 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29819400/

相关文章:

c# - 如何处理文件名

C# 从序列化的 json 数组访问值

c# - 有没有更好的方法来执行此操作(C#)?

c# - 以编程方式访问资源文件中的值

java - ANTLR4 在较长的文件上抛出 java.lang.StackOverflowError

python - 有没有办法自动生成有效的算术表达式?

python - 将长数字格式化为字符串

parsing - 有关将语法树转换为程序集的资源?

c++ - 为什么得到的MachineGuid看起来不像是GUID而是韩文?

python - 使用复数时如何限制小数位数