Last active
August 29, 2015 14:11
-
-
Save sangram-chavan/5097ae61e936f41a3b41 to your computer and use it in GitHub Desktop.
Custom TimeSpan Format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Custom TimeSpan formar | |
@"%s", | |
@"%s\.f", | |
@"%s\.f", | |
@"%s\.ff", | |
@"%s\.fff", | |
@"%m\:%s", | |
@"%m\:%s\.f", | |
@"%m\:%s\.ff", | |
@"%m\:%s\.fff", | |
@"%h\:%m\:%s", | |
@"%h\:%m\:%s\.f", | |
@"%h\:%m\:%s\.ff", | |
@"%h\:%m\:%s\.fff" | |
*/ | |
void Main() | |
{ | |
string[] inputs = { | |
@"14:15:16.520", | |
@"14:15:16.52", | |
@"14:15:16.5", | |
@"14:15:16", | |
@"15:16.520", | |
@"15:16.52", | |
@"15:16.5", | |
@"15:16", | |
@"16.520", | |
@"16.52", | |
@"16.5", | |
@"0.5", | |
@"16", | |
}; | |
string[] formats = { | |
@"%s", | |
@"%s\.f", | |
@"%s\.f", | |
@"%s\.ff", | |
@"%s\.fff", | |
@"%m\:%s", | |
@"%m\:%s\.f", | |
@"%m\:%s\.ff", | |
@"%m\:%s\.fff", | |
@"%h\:%m\:%s", | |
@"%h\:%m\:%s\.f", | |
@"%h\:%m\:%s\.ff", | |
@"%h\:%m\:%s\.fff", | |
}; | |
TimeSpan interval; | |
// Parse each string in inputs using formats and the de-DE culture. | |
foreach (string input in inputs) { | |
try { | |
if (TimeSpan.TryParseExact(input, formats, null, out interval)) | |
Console.WriteLine("{0} --> {1}", input, interval.ToString("g")); | |
else | |
Console.WriteLine("Unable to parse '{0}'", input); | |
} | |
catch (FormatException) { | |
Console.WriteLine("{0} --> Bad Format", input); | |
} | |
catch (OverflowException) { | |
Console.WriteLine("{0} --> Overflow", input); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment