Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime ParseExact Throws Exception [closed]

Tags:

c#

datetime

Well i am trying to parse that date

5/10/2013 002704

        var stt = "5/10/2013 002704";
        result = DateTime.ParseExact(stt, "dd-MM-yyyy HHmmss", CultureInfo.InvariantCulture);

but i get this Exception

String was not recognized as a valid DateTime.

However!, this code works to parse only the time *without date*

        var stt = "002704";
        result = DateTime.ParseExact(stt, "HHmmss", CultureInfo.InvariantCulture);

Well i hope someone helps me with that problem and thanks in advance...

HINT : THIS ALSO FAILS

    var stt = "5/10/2013 002704";
    result = DateTime.ParseExact(stt, "dd/MM/yyyy HHmmss", CultureInfo.InvariantCulture);

Well it works! thanks to every one helped me here for his\her very nice help that i really appreciate very much. Also i will take the XY Problem into account next time :D.

like image 492
Roman Ratskey Avatar asked May 04 '26 05:05

Roman Ratskey


2 Answers

Ah, you're doing a parse exact with dd but passing in d. Change your input string to "05/10/2013 002704", and make sure you're using / in your delimiter.

var stt = "05/10/2013 002704";
result = DateTime.ParseExact(stt, "dd/MM/yyyy HHmmss", CultureInfo.InvariantCulture);

Edit

Sorry, I had to take a phone call and couldn't finish my thought. Instead of using dd you probably want d. It will work with 05/10/2013 or any number up to 31 (as pointed out in the comments on the question). Also, I think @DanJ made a great comment reference the use case of this method.

The short answer is, if you're going to use Parse*Exact*(), you'd better be sure the string you're supplying matches the format specifier.

If you are going to move forward with ParseExact then you should use:

result = DateTime.ParseExact(stt, "d/MM/yyyy HHmmss", CultureInfo.InvariantCulture);
like image 142
Jim D'Angelo Avatar answered May 06 '26 19:05

Jim D'Angelo


You have two things wrong:

  1. You are using dd for the day of the month, which expects a leading 0 if the day is a single digit. Use d instead.
  2. As others have said, you are using - in your format, but / in your input data.
like image 27
adrianbanks Avatar answered May 06 '26 19:05

adrianbanks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!