简体   繁体   中英

String was not recognized as a valid DateTime when using DateTime.ParseExact

I have below piece of code to log the message. Since I wanted to have the log for each date I tried to retrieve current date and then tried to create log file with that particular date with format path/dd_mm_yyyy_LogFile.txt . Before that I had to retrieve current date without time.

StreamWrite sw=null;
var d = Convert.ToString(DateTime.Today.ToShortDateString());
var date = DateTime.ParseExact(d, "dd_MM_yyyy", CultureInfo.InvariantCulture);
//Error in the above line  
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\" + d + "_LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + message);

But am getting String was not recognized as a valid DateTime . I followed many other posts like changing the "dd_MM_yyyy" to "dd-MM-yyy" or to "dm-yyyy" but unfortunately am still hitting the same error. What else am missing here? Below screenshot for reference. If you see the screenshot, I've proper d value fetched. But still the above exception.

在此处输入图片说明

As I can see from the picture, you actually want "M/d/yyyy" format:

  String d = @"2/26/2016"; // d's value has been taken from the screenshot
  DateTime date = DateTime.ParseExact(d, "M/d/yyyy", CultureInfo.InvariantCulture);

Your format string in Parse method should exactly match the one produced by ToShortDateString . eg this works with me:

var d = Convert.ToString(DateTime.Today.ToShortDateString());
Console.WriteLine(d);

var date = DateTime.ParseExact(d, @"MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);

output:

02/26/2016                                                                                                                                                                                                                                             
02/26/2016 00:00:00

Look at the screen shot you posted. The runtime value of the string is:

"2/26/2016"

So the format string should be:

"M/dd/yyyy"

or:

"MM/dd/yyyy"

By using those other format strings, you're explicitly telling the system to use that exact format. And the string you have doesn't match that format. Hence the error.

Create d like this instead:

var d = DateTime.Today.ToString("dd_MM_yyyy");

ToShortDateString() does not have the format you want.

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