简体   繁体   中英

String was not recognized as a valid DateTime in asp.net

I am facing an issue while assign value to DateTime stdt please find below my code logic

startdate ="06/20/2016 12:30" //format (MM/dd/yyyy HH:mm)

DateTime stdt = Convert.ToDateTime(startdate);

also, I had tried with below code but didn't work.

DateTime stdt = DateTime.ParseExact(startdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

According your date, you should use :

DateTime stdt = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);

to match each part of your date.

Please see here : https://msdn.microsoft.com/en-US/library/w2sa9yss%28v=vs.110%29.aspx for method usage

And https://msdn.microsoft.com/en-US/library/az4se3k1(v=vs.110).aspx for date patterns

I think this will work:

DateTime stdt = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);

you have to put the formatting of the string that you pass to the method.

如果您不想传递格式,则可以使用区域性:

 var date = DateTime.Parse("06/20/2016 12:30", new CultureInfo("en-US"));

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