Converting date and time in C # - DateTime.ParseExact () not working properly

I have a date / time format, for example: "1-Mar-13 92230" According to this document and this link the format is as follows: "d-MMM-yy Hmmss", because:

Day is single digit, 1-30 Month is 3 letter abbreviation, Jan/Mar etc. Year is 2 digits, eg 12/13 Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09) Minute is standard (eg 01, 52) Second is standard (eg 30, 02) 

I try to run the following code in my program, but I continue to receive the error message "String was not recognized as a valid DateTime."

 string input = "1-Mar-13 92330"; var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss", System.Globalization.CultureInfo.CurrentCulture); 

Please help, I'm not too familiar with DateTime conversions, but I don’t see where I made a mistake here. Thanks!

UPDATE: Is it because time cannot be parsed without colons in between? (e.g. 1-Mar-13 9:22:30 receives parsing, but I have an external data source that cannot be rewritten from Hmmss to H: mm: ss)

+7
c # datetime
source share
4 answers

You can fix your date:

 var parts = "1-Mar-13 92230".Split(' '); if (parts[1].Length == 5) { parts[1] = "0" + parts[1]; } var newDate = parts[0] + " " + parts[1]; var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss", System.Globalization.CultureInfo.CurrentCulture); 
+4
source share

From msdn :

If the format is a custom format template that does not include a date or (for example, "yyyyMMdd HHmm"), use an invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify the clock in the template format, specify a wider form, "HH", instead of a narrower form, "H".

so you can try:

 string input = "1-Mar-13 92330"; var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss", System.Globalization.CultureInfo.InvariantCulture); 
+4
source share

Your input line should have the following format

 string input = "1-Mar-13 092330"; 

If you return to your link, he will say

 H 24-hour clock hour (eg 19) 

Now H is 24 hours, it should be represented by the leader 0. If you can’t imagine how you would deal with a clock greater than 9, that is, with a double digit.

If your hour, minutes and seconds should not be separated.

 string input = "1-Mar-13 9 2330"; var date = DateTime.ParseExact(input, "d-MMM-yy H mmss", System.Globalization.CultureInfo.InvariantCulture); 
+1
source share

Your min hour and second need to be divided, as they do not differ.

 string input = "1-Mar-13 9 23 30"; var date = DateTime.ParseExact(input, "d-MMM-yy H mm ss", System.Globalization.CultureInfo.CurrentCulture); 
0
source share

All Articles