c# - How to convert datetime string in format MMMdyyyyhhmmtt to datetime object? -
i have tried below:
datetime.parseexact("feb520161000pm", "mmmdyyyyhhmmtt", cultureinfo.invariantculture) but it's giving formatexception.
interestingly
datetime.parseexact(datetime.now.tostring("mmmdyyyyhhmmtt"), "mmmdyyyyhhmmtt", cultureinfo.invariantculture) this giving format exception.
alexei's answer quite right, wanna explain little bit deep if let me..
you thinking 5 should match d specifier, right? not how datetime.parseexact works under hood.
since the "d" custom format specifier represents number 1 through 31, specifier map 52 in string, not 5. that's why code throws formatexception.
as can see, string format can't parsed unless string manipulations it.
in such case, .net team suggests either using 2 digit forms 05 or insert separators date , time values.
you can create custom method parse mmmdyyyyhhmmtt format only parse kind of formatted strings like;
public static datetime? parsedate_mmmdyyyyhhmmtt(string date) { if (date == null) return null; if (date.length < 14) return null; if (date.length == 14) date = date.insert(3, "0"); datetime dt; if (datetime.tryparseexact(date, "mmmdyyyyhhmmtt", cultureinfo.invariantculture, datetimestyles.none, out dt)) return dt; return null; }
Comments
Post a Comment