We have an integration partner who insists on sending us datetimes as strings in the format yyyyMMdd:Hmm
, e.g., "20211029:102". Note that the hour does not have a leading zero.
I tried to parse it like this:
Datetime datetime = DateTime.ParseExact(
"20211029:102",
"yyyyMMdd:hmm",
CultureInfo.InvariantCulture,
DateTimeStyles.None
);
But this results in
FormatException••• String '20211029:102' was not recognized as a valid DateTime.
I can make it work by re-adding the missing zero, something like:
string datetimeParts = "20211029:102".Split(":");
string value = datetimeParts[0] + datetimeParts[1].PadLeft(4, '0');
Datetime dt = DateTime.ParseExact(
value,
"yyyyMMddHHmm",
CultureInfo.InvariantCulture,
DateTimeStyles.None
);
But I feel I shouldn't need to "preparse" the value. Is it possible to parse this format without pre-processing?