Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, parsing a date from string error

Tags:

c#

In the C#, I am parsing a date from string, but it gives me error

DateTime.Parse("07/26/2012");

the error

 System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.DateTime.Parse(String s)

is it related to date format ? is it related to my pc setting ?

Thanks

like image 981
user595234 Avatar asked Dec 09 '22 22:12

user595234


2 Answers

By default, Parse uses your current culture. ParseExact allows you to manually specify the date format.

Try this instead:

DateTime date = DateTime.ParseExact("07/26/2012", "MM/dd/yyyy", CultureInfo.InvariantCulture);

The InvariantCulture option allows you to ignore the current culture settings on the system.

like image 70
Polynomial Avatar answered Jan 02 '23 13:01

Polynomial


Maybe the culture in which you are running this is not compatible with this date format. You could use InvariantCulture:

DateTime.Parse("07/26/2012", CultureInfo.InvariantCulture);

Remember that the Parse method uses the current thread culture.

like image 36
Darin Dimitrov Avatar answered Jan 02 '23 11:01

Darin Dimitrov