Tryparse 对我不起作用,ParseExact 可以,但是当包含额外的 space 时它会失败

Tryparse not working for me and ParseExact works but it fails when extra space is included

Tryparse 对我不起作用,ParseExact 可以,但是当包含额外的 space 时它会失败:

//Tryparse
string dateTimeString = "Sep 10 08:19";
DateTime dateAndTime;

if (DateTime.TryParse(dateTimeString, out dateAndTime))
{
    string temp = dateAndTime.ToString();   //"9/21/2018 10:08:00 AM" ??????? why?
}

//ParseExact works fine but it won't work with extra spaces in the date
string format = "MMM d HH:mm";
//dateTimeString = "Sep 10 08:19"; //works fine with this string
dateTimeString   = "Sep  9 08:19"; //notice extra extra space between "Sep" and "9"
dateAndTime = DateTime.ParseExact(dateTimeString, format, System.Globalization.CultureInfo.InvariantCulture); //Exception here
string temp2 = dateAndTime.ToString();

有什么想法吗?谢谢

所以首先你应该使用 TryParseExact() 而不是 ParseExact() 因为这是与 TryParse().

的正确比较方法

接下来你只需要向你的方法传递一个额外的参数,DateTimeStylesDateTimeStyles.AllowWhiteSpaces:

if(DateTime.TryParseExact(
   "Sep 10 08:19", 
   "MMM d HH:mm", 
   CultureInfo.InvariantCulture, 
   DateTimeStyles.AllowWhiteSpaces, 
   out dateAndTime))
{
    //Parsed correctly, do something
}

Fiddle here