1

I have a string date = 13/07/15 in this format and I want to convert it into DateTime, but I get the error mentioned below

String was not recognized as a valid DateTime.

What can I do to convert into datetime. I have tried this

DateTime dt = Convert.ToDateTime(date);
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Show how are you converting it to `DateTime` –  Jul 27 '15 at 07:10
  • possible duplicate of [String was not recognized as a valid DateTime " format dd/MM/yyyy"](http://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy) – Martin Jul 27 '15 at 07:10
  • 1
    Does the culture on the server accept dates in the format `dd/MM/yyyy`? –  Jul 27 '15 at 07:22
  • `DateTime` probably expects a string in "dd/mm/yy hour:min" so either add the time to your string to make it a valid `DateTime` or format it according to your needs. – ardatosun Jul 27 '15 at 08:11
  • 1
    When you use that overload, the string is parsed with the current culture of the current thread. We do not know what that culture is? You can specify a culture where you know the parse will succeed, for example `Convert.ToDateTime("13/07/15", new CultureInfo("en-GB"))` since British culture allows this "little-endian" order with slashes as separators. It also works with `"fa-IR"` (which means Persian/Farsi in Iran). It does not work with `"en-US"` or `""` cultures; they want the month first. – Jeppe Stig Nielsen Jul 27 '15 at 08:43

3 Answers3

1

Never noticed that different cultures write their data and time in different formats? Although the format you use is valid in most Western European countries it is rubbish in the United States.

To overcome this problem, you can ask the system for the current date and time format:

var currentCulture = System.Globalization.CultureInfor.CurrentCulture
IFormatProvider dateTimeFormat = currentCulture.DateTimeFormat;
string dateTxt = @"13/7/2015";
System.DateTime myDate = System.DateTime.Parse(dateTxt, dateTimeFormat);

That should do the trick if your computer has the correct culture.

If you want to be able to understand a lot of cultures, don't ask for the current culture but use one of the constructors of System.Globalization.CultureInfo

Not wise, because does 1/3/2015 mean March 1st, or January 3rd?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
0

Do like this,

DateTime date = DateTime.ParseExact(s, "dd/MM/yy", null);

Source : DateTime.ParseExact

gkrishy
  • 756
  • 1
  • 8
  • 33
0

Your code DateTime dt = Convert.ToDateTime(date); is perfect. Seems to me like the error is in your database, because it converts it into date if it gets the full year. Please check it in your database.

Nathan Wakefield
  • 105
  • 1
  • 11
vatsal
  • 262
  • 2
  • 13