假设我有一个绑定(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/