我已经张贴在DateTime的一个问题字符串转换,我得到了许多令人满意的答案..所以我感谢StackOverflow的非常..结果这里是字符串manupulation多了一个问题,我坚持.. 结果我使用C#代码将字符串转换(从一些外部源)..字符串可以有日期时间..结果
I had posted a question on DateTime to String conversion, I got many satisfying answers for that .. so I thank StackOverflow very much .. Here is one more problem of String manupulation, I am stuck with .. I have to convert a string (from some external source) using C# code .. the string can have these expected format of DateTime ..
我用 DateTime的尝试(转换.ToInt32(string_date.Substring(6,4)),INT,INT,INT,INT,INT,INT)结果的即通过提取月份,日等值的搜索结果,但它不工作..因为我不能完美地串提取值..作为字符串的长度为变结果我也有试图提取指的/,则次数值空格和:,但它成为瓶颈带AM / PM搜索结果的(非)发生派生的日,月,营业时间只有长度可以改变.. 的结果
I tried using DateTime(Convert.ToInt32(string_date.Substring(6,4)),Int,Int,Int,Int,Int,Int) ie, By extracting the values of month, Day etcBut it doesn't work .. because I can't extract the values with substring perfectly .. as the length of string is Varying I also have tried to extract the values referring the occurance of "/", "space" and ":" but it becomes bottle neck to derive with (non-)Occurrence of AM/PM Only the length of Day, Month and Hours can vary ..
推荐答案可以使用 DateTime.ParseExact 重载需要的格式列表:
You can use the DateTime.ParseExact overload that takes a list of formats:
private static string[] formats = new string[] { "MM/dd/yyyy HH:mm:ss tt", "MM/dd/yyyy HH:mm:ss", "M/dd/yyyy H:mm:ss tt", "M/dd/yyyy H:mm:ss" }; private static DateTime ParseDate(string input) { return DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None); }这将抛出一个 FormatException 如果传递的字符串不匹配任何给定的格式。请注意,预计AM / PM的格式应该相同格式,无需AM / PM(MM / DD / YYYY HH:MM:SS TT出现之前到来之前MM / DD / YYYY HH:MM:SS。)
This will throw a FormatException if the passed string does not match any of the given formats. Notice that the formats expecting AM/PM should appear before identical formats without AM/PM ("MM/dd/yyyy HH:mm:ss tt" comes before "MM/dd/yyyy HH:mm:ss").
更新结果以亨克在评论指出,当使用相同的功能可用 TryParseExact 从而消除异常情况。此外,搭配可空类型这可以稍作清洁:
Update As Henk points out in the comments, the same functionality is available when using TryParseExact which removes exception situation. Also, paired with nullable types this can be made a bit cleaner:
private static DateTime? ParseDate(string input) { DateTime result; if (DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) { return result; } return null; }现在它只会如果无法解析输入返回空引用。
Now it will simply return a null reference if it fails to parse the input.
更多推荐
C#:如何字符串转换为DateTime,其中字符串可以有任何标准的datetime格式
发布评论