Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime TryParseExact and padding

Tags:

c#

.net

datetime

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.

Question

How can I tell the parser to interpret 2 as 02 so that the above parses successfully?

What I've Tried

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.


2 Answers

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)
like image 168
Dmitry Bychenko Avatar answered Feb 18 '26 12:02

Dmitry Bychenko


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]);
like image 21
x2bool Avatar answered Feb 18 '26 12:02

x2bool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!