简体   繁体   中英

String was not recognized as a valid DateTime. 6-26-2015

I tried several Q&A in here and made this piece of code: The idea is to compare dt1 with dt2 and do something later.

date = row.Cells[3].Value.ToString();
DateTime dt1 = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture);
dt1 = dt1.AddDays(-4);
String dateStr = DateTime.Now.ToString("M/d/yyyy");
DateTime dt2 = DateTime.ParseExact(dateStr, "M/d/yyyy", CultureInfo.InvariantCulture);    

On the last line I am having this exception:

String was not recognized as a valid DateTime.

While debugging this are the values:
date = 06/05/2015
dt1 = "01-Jun-15 12:00:00 AM
datestr = 6-26-2015

Your format is incorrect if datestr value is "6-26-2015" you should use this:

DateTime dt2 = DateTime.ParseExact(dateStr, "M-d-yyyy", CultureInfo.InvariantCulture); 

ParseExact tries to match the input string with the given format.

In your case input string is 6-26-2015 and format is M/d/yyyy , - and / can not be matched so the exception is thrown.

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