I'm calling TryParse on a string that I want to parse as a DateTime. Simple stuff. And it all works when the format is as I'd expect. But when each component/some of the components of the date are a single figure, the parse fails.
Example:
var dateFormat = "yyyy-dd-MM hh:mm:ss";
var dateString = "2006-4-1 2:3:5";
DateTime.TryParseExact(dateString, dateFormat,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result)
If I change my dateString to "2006-04-01 02:03:05", it parses fine.
How can I tell the parser to interpret 2 as 02 so that the above parses successfully?
Manually padding each part of the date time to ensure it fits the format. This works, but it doesn't feel very elegant. Is this the only way?
I've also tried, with no success, to use a format like m instead of mm.
Just use
// please note single letters (d, M, h, m, s) whenever you allow single digits
var dateFormat = "yyyy-d-M h:m:s";
And you'll get it:
var dateString = "2006-4-1 2:3:5";
DateTime.TryParseExact(dateString, dateFormat,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result)
With regular expression:
int[] n = new Regex("[^0-9]+").Split("2006-4-1 2:3:5").Select(int.Parse).ToArray();
var datetime = new DateTime(n[0], n[1], n[2], n[3], n[4], n[5]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With