Reputation: 5670
I am converting one string to DateTime variable like this
DateTime selecteddatetest = Convert.ToDateTime("09/21/2017");
This works fine in my production Server, But when I run this code in my local development machine, this throws an error
System.FormatException: 'String was not recognized as a valid DateTime.'
Can anyone please point out what I am missing here?
Upvotes: 0
Views: 2210
Reputation: 14541
You could use ParseExact
if the time format is consistent:
DateTime.ParseExact("09/21/2017","MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture)
Upvotes: 7
Reputation: 8194
You are likely using a different culture between the two machines.
For example, the server is using the US culture which expects the format MM/dd/yyyy
so your parsing works.
You local machine may be using a culture such as UK which expects the format dd/MM/yyyy
and as there is no month 21 it fails.
You can specify the culture explicitly if you know it's always going to be the same:
Convert.ToDateTime("09/21/2017", new System.Globalization.CultureInfo("en-US"));
It may also work with an invariant culture:
Convert.ToDateTime("09/21/2017", System.Globalization.CultureInfo.InvariantCulture);
You may also use ParseExact
to specify the desired format:
DateTime.ParseExact("09/21/2017", "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 2
Reputation: 4319
Its probably a localisation issue between the two machines, try specifying the date in the format "2017-09-21" and it should work everywhere.
Upvotes: 3