Tryparse对我不起作用,并且ParseExact可以工作,但是当包含额外空间时它会失败:

//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
}


小提琴here

09-25 21:20