Reputation:
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);
Upvotes: 1
Views: 3140
Reputation: 262
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.
Upvotes: 0
Reputation: 30492
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?
Upvotes: 1
Reputation: 756
Do like this,
DateTime date = DateTime.ParseExact(s, "dd/MM/yy", null);
Source : DateTime.ParseExact
Upvotes: 0