I'm new to c# how can I convert my input string in to DateTime.
_toDate = 5/22/2015
I cannt use
DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);
Or
Convert.ToDateTime(_toDate)
throw an exception String was not recognized as a valid DateTime.
Note : String shold be excact the same as above.
Appreciate your reply
Clearly, your string and format does not match.
From documentation ;
Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly .
You need to use M/dd/yyyy
with a culture that has /
as a DateSeparator
like InvariantCulture
.
string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
When you use null
as an IFormatProvider
, it's threaded as your CurrentCulture
and if your CurrentCulture
doesn't have /
as a DateSeparator
, you will get FormatException
because /
custom format specifier has a special meaning as replace me with current culture or supplied culture date separator .
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.