简体   繁体   中英

String was not recognized as a valid DateTime when string is 13/07/15

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);

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?

Do like this,

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

Source : DateTime.ParseExact

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM