Reputation: 3342
I am parsing a date from a bank deposit report, and the format is like this:
Jul 9 2015
Jun 20 2015
Basically MMM dd yyyy
except that the single digit day does not contain a leading zero. Is there a simple way to do conditional formatting in DateTime.ParseExact()
? Or will I have to pre-process the date string and either add the leading zero or remove the extra space?? Here is what works for the single digit day dates:
Dim dtDepositDate As DateTime
dtDepositDate = DateTime.ParseExact(strDate, "MMM d yyyy", CultureInfo.InvariantCulture)
and obviously, MMM dd yyyy
would work for the two digit dates, but would not work for the single digit dates with an extra space in between.
Upvotes: 1
Views: 504
Reputation: 223282
For single/double digit day part
Use single d
which is good for both single and double digits day value.
Having single d
would effect the values if the DateTime
is converted to string
. As far as parsing is concerned, it will work for both single and double digits day values, like 01
, 1
, 11
, 20
etc. The same is true for M
, H
, m
, specifier for Month
, Hour
Minutes
etc.
For multiple spaces
For multiple spaces use DateTimeStyles.AllowWhiteSpaces
in parsing.
DateTime dt = DateTime.ParseExact("Jul 9 2015", "MMM d yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces);
or for double digit day part:
DateTime dt = DateTime.ParseExact("Jun 20 2015", "MMM d yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces);
Upvotes: 2