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

Recommended Answers

All 2 Replies

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"));

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! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.