Skip to content

Instantly share code, notes, and snippets.

@sangram-chavan
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangram-chavan/5097ae61e936f41a3b41 to your computer and use it in GitHub Desktop.
Save sangram-chavan/5097ae61e936f41a3b41 to your computer and use it in GitHub Desktop.
Custom TimeSpan Format
/* 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