Parsing "HH:mm:ss" and "H:m:s" times using DateTime.ParseExact()
I want to be able to parse the fol开发者_开发问答lowing times using ParseExact() function:
01:02:03
1:02:03
1:2:03
1:02:3
01:2:3
1:2:3
Is it possible, or do I need to do my own conversions so it work?
So far I can parse only all with leading 0 or all without leading zero. I can do it with 6 format strings but i think this is pretty stupid.
Using ParseExact
with the "H:m:s" custom format string works perfectly for all the examples given in your question.
string[] test = { "01:02:03", "1:02:03", "1:2:03", "1:02:3", "01:2:3", "1:2:3" };
foreach (string s in test)
{
DateTime d = DateTime.ParseExact(s, "H:m:s", null);
Console.WriteLine(d);
}
Have you tried this? All strings parse without a problem in this sample code:
using System;
class Program {
static void Main(string[] args) {
string[] dates = new string[] { "01:02:03", "1:02:03", "1:2:03", "1:02:3", "01:2:3", "1:2:3" };
foreach (string date in dates) {
DateTime dt = DateTime.ParseExact(date, "H:m:s", null);
Console.WriteLine(dt);
}
Console.ReadLine();
}
}
Output:
11/9/2009 1:02:03 AM
11/9/2009 1:02:03 AM
11/9/2009 1:02:03 AM
11/9/2009 1:02:03 AM
11/9/2009 1:02:03 AM
11/9/2009 1:02:03 AM
I think the purpose of ParseExact()
requires an exact match of the format string. Is there a reason not to simply use the Parse()
method instead?
Why not just use Parse
? As its name implies, ParseExact
is used when you have exactly one input format and all others must be rejected.
精彩评论