Joper
Joper

Reputation: 8219

Date time TryParse issue

I am reading csv file where one of tha columns has date format like tat: Day/Month/Year eg: 30/07/2010

But when i am using DateTime.TryParse() to parse that sting in to datetinme method TryParse() treated first numbers like month (number 30 in example above), so i am getting incorrect date exception.

How may i say to Datetime.TryParse() that first numbers in string is day and not a month?

UPDATE:

Why if i changed date to Month/Day/Year eg: 7/30/2010

this not working:

DateTime.TryParseExact("7/30/2010", "m/dd/yyyy", null, DateTimeStyles.None, out date);

Any thoughts?

Upvotes: 1

Views: 888

Answers (4)

Clayton
Clayton

Reputation: 5350

Use the DateTime.TryParseExact method

DateTime dateValue;
var dateString = "30/07/2010";
DateTime.TryParseExact(dateString, "dd/MM/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);

Upvotes: 1

Ed Chapel
Ed Chapel

Reputation: 6932

Try using TryParseExact() and pass the format for your date

DateTime.TryParseExact("30/07/2010", "dd/MM/yyyy", null, DateTimeStyles.None, out result)

Upvotes: 0

ysrb
ysrb

Reputation: 6740

Try:

DateTime.ParseExact(string, "dd/MM/yyyy", null);

Upvotes: 0

Alastair Pitts
Alastair Pitts

Reputation: 19601

Have a look into using a custom date and time format string.

Also, to use a custom format string, you need to use TryParseExact, ala:

DateTime dt;
DateTime.TryParseExact(dateTime, 
                       "dd/MM/yyyy", 
                       CultureInfo.InvariantCulture, 
                       DateTimeStyles.None, 
                       out dt);

Upvotes: 2

Related Questions