0

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?

Equalsk
  • 7,954
  • 2
  • 41
  • 67
None
  • 5,582
  • 21
  • 85
  • 170
  • 2
    You probably have a different culture between the machines, so the server is using the US format and your machine uses something else like UK. Obviously there is no month 21 in the UK. Specify the correct culture or use DateTime.ParseExact with the format you expect. – Equalsk Sep 20 '17 at 11:04
  • You are using a different locale on your production server and your local environment. – oerkelens Sep 20 '17 at 11:04
  • use DateTime.ParseExact https://stackoverflow.com/a/1368681/971839 – halit Sep 20 '17 at 11:05
  • Possible duplicate of [Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"](https://stackoverflow.com/questions/1368636/why-cant-datetime-parseexact-parse-9-1-2009-using-m-d-yyyy) – halit Sep 20 '17 at 11:06
  • Possible duplicate of [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – SᴇM Sep 20 '17 at 11:09
  • `Convert.ToDateTime("09/21/2017", CultureInfo.InvariantCulture);` otherwise your local date separator is used because `/` is a custom format specifier that says: please replace me with the actual date separator – Tim Schmelter Sep 20 '17 at 11:10

3 Answers3

6

You could use ParseExact if the time format is consistent:

DateTime.ParseExact("09/21/2017","MM/dd/yyyy", 
                     System.Globalization.CultureInfo.InvariantCulture)
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
3

Its probably a localisation issue between the two machines, try specifying the date in the format "2017-09-21" and it should work everywhere.

gmn
  • 4,199
  • 4
  • 24
  • 46
2

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);
Equalsk
  • 7,954
  • 2
  • 41
  • 67