0

Hey guys,

Just wondering if you could assist me quickly with some validation.

I have some strings in for the format:

MM:SS.mm

Where MM = Minutes, SS = Seconds, mm = Milliseconds.

I'm just wondering whether you can help me with how to validate to ensure an input string is in this correct format? I don't necessarily need any answers but maybe some links to some literature I can read up on it? Google'ing just seems to return fully-fledged DD/MM/YY HH:mm:ss which isn't what I am after.

At the moment I am trying DateTime.ParseExact(...) but this throws FormatExceptions when I try to input my string. I have also tried to find some Regex expressions to no avail.

Any help is greatly appreciated - Thank you!

- Awslc

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by awslc
2

Are you using the correct format string for ParseExact()? Also note that if you just want to verify the formatting, TryParseExact() would be a better option due to returning bool instead of throwing an exception on failure:

CultureInfo culture = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.AssumeLocal;
string time = "44:22.37";
DateTime dummy;

if (DateTime.TryParseExact(time, "mm:ss.ff", culture, style, out dummy))
    Console.WriteLine(dummy.ToString("mm:ss.ff"));
0

Are you using the correct format string for ParseExact()? Also note that if you just want to verify the formatting, TryParseExact() would be a better option due to returning bool instead of throwing an exception on failure:

CultureInfo culture = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.AssumeLocal;
string time = "44:22.37";
DateTime dummy;

if (DateTime.TryParseExact(time, "mm:ss.ff", culture, style, out dummy))
    Console.WriteLine(dummy.ToString("mm:ss.ff"));

Excellent!

Thank you - at the moment I had ParseExact() in it's own method returning a boolean. This isn;t needed now thanks to the TryParseExact() so thank you. It seemed I had an issue with the format string beforehand.

Thanks for your answer! :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.