if i have a datetime string in a weird format, such as YYYY##MM##DD HH**M**SS, how can i create a new datetime object base on that? i have read something about the datetimeformatinfoclass but not sure how to get it working..
if i have a datetime string in a weird format, such as YYYY##MM##DD HH**M**SS
Share
You can use DateTime.ParseExact, or DateTime.TryParseExact for data which you’re not confident in. For example:
The quotes in the format string aren’t strictly necessary – this will work too:
However, using the quotes means you’re being explicit that the characters between the quotes are to be used literally, and not understood as pattern characters – so if you changed “#” to “/” the version using quotes would definitely use “/” whereas the version without would use a culture-specific value.
The
nullin the call toParseExactmeans “use the current culture” – in this case it’s unlikely to make much difference, but a commonly useful alternative isCultureInfo.InvariantCulture.It’s unfortunate that there’s no way of getting the BCL to parse the format string and retain the information; my own Noda Time project rectifies this situation, and I’m hoping it’ll make parsing and formatting a lot faster – but it’s far from production-ready at the moment.