Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting "August 2012" to DateTime object with TryParseExact

I am trying to parse a string that is of the format "August 2012" into a DateTime object. The string is coming from the column name in a DataTable.

string columnName= row[col].ToString(); // "August 2012"

Initially I tried using DateTime.TryParse() ...

bool result = DateTime.TryParse(row[col].ToString, out convertedDateTime);

but it kept returning false. So next I tried using DateTime.TryParseExact using the the proper cultureformat as described here ...

CultureInfo enUS = new CultureInfo("af-ZA");
DateTime.TryParseExact(row[col].ToString(), "y", enUS, DateTimeStyles.None, out columnNameAsDate)

However, this keep returning false also. What am I doing wrong? SHouldn't I be able to parse a string in the format August 2012 into a DateTime object?

like image 605
webworm Avatar asked May 21 '26 00:05

webworm


1 Answers

This should give you the date expected.

string columnName= row[col].ToString();  // ==> August 2012
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(columnName, "MMMM yyyy", enUS, DateTimeStyles.None, out columnNameAsDate);

First: You should specify the exact culture. In af-ZA culture the eighth month of the year is named "Augustus" not "August" and this will, of course, fail.

Second: You should pass the correct format specification to get the full month name (MMMM) and the year (yyyy).

like image 148
Steve Avatar answered May 23 '26 12:05

Steve